`__slots__`: Up to 20% Faster Attribute Access by Bypassing `__dict__`
Using `__slots__` in Python classes can improve attribute access speed by 10-20% and reduce memory usage by preventing the creation of an instance `__dict__` for each object. This optimization, originally a fallback for new-style class performance, directly reserves space for declared attributes, bypassing slower dictionary lookups.
The top 3
- `__slots__` Memory Magic: Fixed Array vs. Dynamic Dict: Defining `__slots__` replaces Python's default dynamic `__dict__` for attribute storage with a fixed-size array, eliminating per-instance dictionary overhead and enabling faster attribute access via direct memory offsets. This can lead to substantial memory savings, especially for numerous small objects, with reductions ranging from 25% to over 70% in some cases, though Python 3.11+ optimizations typically yield 32-64 bytes per instance.
- `__slots__`'s Price: Lost Flexibility & Inheritance Quirks: The main trade-off for `__slots__`'s efficiency is reduced flexibility: instances cannot dynamically add new attributes, resulting in an `AttributeError` if attempted. It also complicates class hierarchies, as subclasses must define their own `__slots__` to inherit the benefits, and multiple inheritance with non-empty `__slots__` in multiple parent classes can be particularly challenging. Additionally, instances lose the ability to be targets of weak references by default.
- __slots__ Memory Magic: Fixed Array vs. Dynamic Dict: `__slots__` replaces the traditional `__dict__` for instance attributes with a fixed-size array, significantly reducing memory footprint and speeding up attribute access by avoiding dictionary lookups.
Sources
Open the full topic