Suppose I have a class with __slots__
class A:
__slots__ = ['x']
a = A()
a.x = 1 # works fine
a.y = 1 # AttributeError (as expected)
Now I am going to change __slots__
of A
.
A.__slots__.append('y')
print(A.__slots__) # ['x', 'y']
b = A()
b.x = 1 # OK
b.y = 1 # AttributeError (why?)
b
was created after __slots__
of A
had changed, so Python, in principle, could allocate memory for b.y
. Why it didn't?
How to properly modify __slots__
of a class, so that new instances have the modified attributes?
You cannot dynamically alter the
__slots__
attribute after creating the class, no. That's because the value is used to create special descriptors for each slot. From the__slots__
documentation:You can see the descriptors in the class
__dict__
:You cannot yourself create these additional descriptors. Even if you could, you cannot allocate more memory space for the extra slot references on the instances produced for this class, as that's information stored in the C struct for the class, and not in a manner accessible to Python code.
That's all because
__slots__
is only an extension of the low-level handling of the elements that make up Python instances to Python code; the__dict__
and__weakref__
attributes on regular Python instances were always implemented as slots:All the Python developers did here was extend the system to add a few more of such slots using arbitrary names, with those names taken from the
__slots__
attribute on the class being created, so that you can save memory; dictionaries take more memory than simple references to values in slots do. By specifying__slots__
you disable the__dict__
and__weakref__
slots, unless you explicitly include those in the__slots__
sequence.The only way to extend slots then is to subclass; you can dynamically create a subclass with the
type()
function or by using a factory function:You cannot modify the
__slots__
attribute after class creation. This is because it would leade to strange behaviour.Imagine the following.
What should happen in this scenario? No space was originally allocated for a second slot, but according to the slots attribute,
a
should be able have space fory
.__slots__
is not about protecting what names can and cannot be accessed. Rather__slots__
is about reducing the memory footprint of an object. By attempting to modify__slots__
you would defeat the optimisations that__slots__
is meant to achieve.How __slots__ reduces memory footprint
Normally, an object's attributes are stored in a
dict
, which requires a fair bit of memory itself. If you are creating millions of objects then the space required by these dicts becomes prohibitive.__slots__
informs the python machinery that makes the class object that there will only be so many attributes refered to by instances of this class and what the names of the attributes will be. Therefore, the class can make an optimisation by storing the attributes directly on the instance rather than in adict
. It places the memory for the (pointers to the) attributes directly on the object, rather than creating a newdict
for the object.It appears to me a type turns
__slots__
into a tuple as one of it's first orders of action. It then stores the tuple on the extended type object. Since beneath it all, the python is looking at atuple
, there is no way to mutate it. Indeed, I'm not even sure you can access it unless you pass a tuple in to the instance in the first place.The fact that the original object that you set still remains as an attribute on the type is (perhaps) just a convenience for introspection.
You can't modify
__slots__
and expect to have that show up somewhere (and really -- from a readability perspective, You probably don't really want to do that anyway, right?)...Of course, you can always subclass to extend the slots:
Putting answers to this and related question together, I want to make an accent on a solution to this problem:
Consider the following module which declares some classes:
module.py:
Here's how you can add attributes to these classes:
But what if you receive class instances from some third-party module using the
module
?module_3rd_party.py:
No problem, it will also work! The only difference is that you may need to patch them before you import third-party module (in case it imports classes from the
module
):It works because Python imports modules only once and then shares them between all other modules, so the changes you make to modules affect all code running along yours.