- 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 viaPyTypeObject
?

- 40,168
- 10
- 71
- 80

- 112,946
- 110
- 377
- 526
-
Can't you just assign to the `__slots__` attribute from the C interface just as you would in a .py file? – David Heffernan Feb 20 '11 at 15:14
-
@David Heffernan: Only on non-legacy systems `;)`. – Matt Joiner Feb 21 '11 at 00:04
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. :-)

- 167,292
- 41
- 224
- 251
-
PyObject_GenericDelAttr = PyObject_GenericSetAttr with a NULL value argument. – ncoghlan Feb 21 '11 at 00:45
-
3Huh, the C API docs are really slack on documenting the fact that the tp_setattr and tp_setattro methods are supposed to handle deletion as well. We should probably do something about that... – ncoghlan Feb 21 '11 at 00:51
-
2For more detail on how __slots__ is implemented, the Python near-equivalent at http://code.activestate.com/recipes/532903-how-__slots__-are-implemented/ is worth looking at. – joeln Feb 23 '14 at 04:48