· Hakan Çelik · Python · 1 dk okuma

Auto Slots

Automatically generate __slots__ from __init__ parameters using a metaclass and co_names.
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

In Python, everything is an object and every object has a type — including primitives, functions, and classes themselves. type() and __class__ reveal this relationship.

Run Methods Order In Python

Run Methods Order In Python

Python · 2 dk

Which method runs when in Python metaclasses? The execution order of __prepare__, __new__, __init__, and __call__ during class definition and instance creation.