7.7 Optimizing small objects with __slots__
The general case for an object allows a dynamic collection of attributes. There’s a special case for an object with a fixed collection of attributes based on the tuple class. We looked at both of these in the Using typing.NamedTuple for immutable objects recipe.
There’s a middle ground. We can also define an object with a fixed number of attributes, but the values of the attributes can be changed. By changing the class from an unlimited collection of attributes to a fixed set of attributes, it turns out that we can also save memory and processing time.
How can we create optimized classes with a fixed set of attributes?
7.7.1 Getting ready
Generally, Python allows adding attributes to an object. This can be undesirable, particularly when working with a large number of objects. The flexibility of the way most class definitions use a dictionary has a cost in memory use. Using...