__slots__
implemented in Python?__slots__
behaviour when defining a Python class in C via PyTypeObject
?Python | Use of __slots__ slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.
Slots in Python is a special mechanism that is used to reduce memory of the objects. In Python, all the objects use a dynamic dictionary for adding an attribute. Slots is a static type method in this no dynamic dictionary are required for allocating attribute.
Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key. Syntax : getattr(obj, key, def) Parameters : obj : The object whose attributes need to be processed.
All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.
When creating Python classes, they by default have a __dict__
and you can set any attribute on them. The point of slots is to not create a __dict__
to save space.
In the C interface it's the other way around, an extension class has by default no __dict__
, and you would instead explicitly have to add one and add getattr/setattr support to handle it (although luckily there are methods for this already, PyObject_GenericGetAttr
and PyObject_GenericSetAttr
, so you don't have to implement them, just use them. (Funnily there is not PyObject_GenericDelAttr, though, I'm not sure what that is about. (I should probably stop nesting parenthesis like this (or not)))).
Slots therefore aren't needed nor make sense for Extension types. By default you just let your getattr/setatttr methods access only those attributes that the class has.
As for how it's implemented, the code is in typeobject.c, and it's pretty much just a question of "If the object has a __slots__
attribute, don't create a __dict__
. Quite unexciting. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With