Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is __slots__ implemented in Python?

  • How is __slots__ implemented in Python?
  • Is this exposed in the C interface?
  • How do I get __slots__ behaviour when defining a Python class in C via PyTypeObject?
like image 547
Matt Joiner Avatar asked Feb 20 '11 15:02

Matt Joiner


People also ask

What does __ slots __ mean in Python?

Python | Use of __slots__ slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.

How do Python slots work?

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.

What is Getattr Python?

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.

What is __ dict __ in Python?

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.


1 Answers

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. :-)

like image 197
Lennart Regebro Avatar answered Sep 16 '22 15:09

Lennart Regebro