So, while working my way through my current project, I came across the notion of a ‘slot’ as discussed here. And I wondered, what the Hell is a slot?
A slot is nothing more than a memory management nicety: when you define __slots__ on a class, you’re telling the Python interpreter that the list of attributes described within are the only attributes this class will ever need, and a dynamic dictionary is not needed to manage the references to other objects within the class. This can save enormous amounts of space if you have thousands or millions of objects in memory.
For example, if you define:
class Foo: __slots__ = ['x'] def __init__(self, n): self.x = n y = Foo(1) print y.x # prints "1" y.x = 2 print y.x # prints "2" y.z = 4 # Throws exception. print y.z
Without the __slots__ definition, that last assignment would have worked. Without any other magic (say, overrides of getattr or setattr), you can always assign attributes to an object. But with a __slots__ definition, you can’t: python hasn’t allocated a dictionary for the object, so you’re stuck with what you’ve got and nothing more.
Slots should only be used as a memory optimization tool; using it to constrain attribute management is silly, and breaks important features like static serialization.