Benefits of using __slots__
Class instances in Python can hold instance variables. Due to Python’s dynamic nature, these variables live within a dictionary (__dict__
) for a given class instance.
class Example:
...
foo = Example()
foo.name = "name"
foo.age = 10
The special attribute __slots_
works as an alternative to __dict__
as when explicitly stated in the class definition, allows you to define the attributes the class instances can have. This also means that instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions other than the slots mentioned when creating the class.
class Example:
__slots__ = 'name'
...
foo = Example()
foo.name = "name"
foo.age = 10 # AttributeError
The benefits of doing this is that, since you no longer need a dictionary to hold you instance variables, you will end up with faster attribute access and space savings in memory.