· Hakan Çelik · Python · 1 dk okuma

Auto Slots

__slots__ belleği optimize eder ama her sınıfa elle eklemek zahmetlidir. Metaclass ve co_names kullanarak __init__ parametrelerinden otomatik __slots__ üreten bir yaklaşımı anlattım.
class Meta(type):
    def __new__(mcs, name, bases, namespace, **kwargs):
        __slots__ = namespace.get("__slots__", ())
        if not __slots__:
            if __init__ := namespace.get("__init__", None):
                __slots__ = __init__.__code__.co_names
                namespace["__slots__"] = __slots__
        return super().__new__(mcs, name, bases, namespace, **kwargs)

class AutoSlots(metaclass=Meta):
    pass

class Example(AutoSlots):
    def __init__(self, field: str, *, keyword_field: int):
        self.field = field
        self.keyword_field = keyword_field
        self.constant = "constant"

assert Example.__slots__ == ("field", "keyword_field", "constant")
assert Example("field", keyword_field=1).__dict__ == {}
Back to Blog

Related Posts

View All Posts »
Understanding Python Classes

Understanding Python Classes

Python · 2 dk

Python'da her şey nesnedir ve her nesnenin bir tipi vardır — primitifler, fonksiyonlar ve sınıfların kendisi de dahil. type() ve __class__ bu ilişkiyi ortaya çıkarır.

Run Methods Order In Python

Run Methods Order In Python

Python · 2 dk

Python metaclass'larında hangi metot ne zaman çalışır? Sınıf tanımı ve örnek oluşturma sırasındaki __prepare__, __new__, __init__, __call__ çalışma sırası.