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):
Using
__slots__
gives memory and performance optimizations.