__slots__ magic
The special attribute __slots__
allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:
faster attribute access.
space savings in memory.
The space savings is from
Storing value references in slots instead of
__dict__
.Denying
__dict__
and__weakref__
creation if parent classes deny them and you declare__slots__
.
Every class can have instance attributes. By default Python uses a dict to store an object’s instance attributes. This allows setting arbitrary new attributes at runtime.
For small classes with known attributes it might be a bottleneck. The dict
wastes a lot of RAM. Python can’t just allocate a static amount of memory at object creation to store all the attributes. Therefore it sucks a lot of RAM if you create a lot of objects (I am talking in thousands and millions). Still there is a way to circumvent this issue. It involves the usage of __slots__
to tell Python not to use a dict, and only allocate space for a fixed set of attributes.
Example:
Without __slots__
:
With __slots__
:
Using __slots__
will reduce the burden on your RAM.
Sidenote: you might want to try PyPy: it does all of these optimizations by default.
Last updated