3

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?

Community
  • 1
  • 1
aturbo
  • 31
  • 2
  • 1
    http://stackoverflow.com/questions/14118564/how-does-slots-avoid-a-dictionary-lookup – DavidW Jan 10 '17 at 09:24
  • `__slots__` is an optimisation feature which does away with the `__dict__` dictionary - hence the optimisation. It has a number of disadvantages. It has to be constructed and maintained 'manually', whereas `__dict__` is dynamic. Second, inherited classes must use it as well, otherwise they might be slower. Thirdly, it breaks code that expects there to be a `__dict__`. – cdarke Jan 10 '17 at 09:25

2 Answers2

4

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.

Dair
  • 15,910
  • 9
  • 62
  • 107
1

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.

Community
  • 1
  • 1
Dmitry
  • 2,026
  • 1
  • 18
  • 22