__slots__
In one line
__slots__ declares fixed attributes, eliminating __dict__ and saving ~40-50% memory per instance.
In simple words
By default, Python objects store attributes in a per-instance __dict__ (a hash table). This is flexible but memory-heavy. For classes with millions of instances, this adds up.
Defining __slots__ = ['x', 'y', 'z'] tells Python to use a fixed-size array instead of a dict. Benefits:
- Memory savings — ~40-50% less per instance (no dict overhead)
- Faster attribute access — array indexing vs hash lookup
- Accidental attribute prevention — assigning an unlisted attribute raises AttributeError
Trade-offs: you lose __dict__, can't easily add new attributes, and some features (multiple inheritance with slots) are tricky. Use when you have many instances of the same class.
Example
import sys
class PointDict:
def __init__(self, x, y):
self.x = x
self.y = y
class PointSlots:
__slots__ = ["x", "y"]
def __init__(self, x, y):
self.x = x
self.y = y
p1 = PointDict(1, 2)
p2 = PointSlots(1, 2)
print(sys.getsizeof(p1.__dict__)) # ~104 bytes (dict)
print(sys.getsizeof(p2)) # Smaller (no dict)
# p2.z = 3 # AttributeError! Not in slots__slots__ replaces __dict__ with a fixed array — less memory, faster access, but you can't add undeclared attributes.
Common confusions
Confused with: frozen dataclass
The difference: __slots__ is about memory optimization — it restricts attributes but they're still mutable. frozen=True on a dataclass is about immutability — attributes can't be changed but memory isn't necessarily optimized. You can combine both: @dataclass(frozen=True, slots=True).
Related terms
Related Resources
Related Lessons
- Python OOP
Using __slots__.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.