Python __slots__ Documentation: Complete 2026 Guide
Unlock Python __slots__ documentation essentials in 2026. This powerful attribute optimizes memory usage in classes, speeding up attribute access by 3-5x compared to standard dict-based instances.
Ideal for data-heavy apps like ML models or games, __slots__ prevents dynamic attributes, enforcing structure. Our guide covers syntax, benefits, pitfalls, and best practices from official docs.
Step 1: Basic Syntax and Declaration
Declare __slots__ as a class attribute listing allowed names. No dict created for instances.
- class Point: __slots__ = ['x', 'y']
- p = Point(); p.x = 1 # Fast access
Step 2: Memory Savings Explained
Instances use fixed slots array, slashing overhead. Test with sys.getsizeof().
- 1. Without slots: ~56 bytes overhead
- 2. With slots: ~32 bytes
- 3. Scale to millions: GBs saved
Step 3: Inheritance and Limitations
Subclasses must declare own __slots__. Can't add dynamic attrs post-slots.
- 1. class Child(Point): __slots__ = ['z']
- 2. No __dict__ or __weakref__ by default
- 3. Use tuple for slots
Step 4: Advanced Usage in 2026 Libraries
NumPy, dataclasses integrate __slots__. Pickle support requires care.
- 1. @dataclass(slots=True)
- 2. Custom __getattr__ hacks avoided
- 3. Profiling tools confirm speed
Step 5: Common Errors and Fixes
Avoid modifying slots post-init. Debug with inspect module.
- 1. AttributeError on missing slots
- 2. Extend via subclassing
- 3. Tools: memory_profiler
Best Practices from Python Docs
Use for value objects in perf-critical codebases.
- Immutable slots with properties
- Combine with typing
- 2026: Async class optimizations