This question: Usage of __slots__? answers that __slots__
can make attribute access faster. But I want to know why?
What happens when we define __slots__
in a class?
This question: Usage of __slots__? answers that __slots__
can make attribute access faster. But I want to know why?
What happens when we define __slots__
in a class?
As for why access is faster Guido talks about it here:
In particular, in order to make data descriptors work properly, any manipulation of an object's attributes first involved a check of the class dictionary to see if that attribute was, in fact, a data descriptor. If so, the descriptor was used to handle the attribute access instead of manually manipulating the instance dictionary as is normally the case. However, this extra check also meant that an extra lookup would be performed prior to inspecting the dictionary of each instance. Thus the use of
__slots__
was a way to optimize the lookup of data attributes—a fallback, if you will, in case people were disappointed with the performance impact of the new class system.
From documentation (slots):
By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.
The default can be overridden by defining
__slots__
in a new-style class definition. The__slots__
declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because__dict__
is not created for each instance.
Using __slots__
gives memory and performance optimizations.