Slots Class: How to Reduce Memory Usage in Python
Use __slots__ to prevent dynamic attribute creation and reduce per-instance memory overhead, while keeping methods intact.
Python code
16 linesclass SlotsDemo:
__slots__ = ("name", "age", "email")
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
def describe(self):
return f"{self.name}, {self.age}, {self.email}"
if __name__ == "__main__":
instance = SlotsDemo("Alice", 30, "alice@example.com")
print(instance.describe())
print(f"Instance dict exists: {'__dict__' in dir(instance)}")
print(f"Total size with slots: {instance.__sizeof__()} bytes")
Output
Alice, 30, alice@example.com
Instance dict exists: False
Total size with slots: 48 bytes
How it works
By defining __slots__, Python allocates a fixed-size array for the attributes listed, instead of a per-instance __dict__. This eliminates the overhead of a dictionary, which stores attribute names as strings and values, and reduces memory usage significantly, especially when creating many instances. The downside is that you can't assign attributes that are not in __slots__, preventing accidental typos and enforcing a strict attribute set. This approach is ideal for classes that act as data containers or value objects.
Common mistakes
- Forgetting that __slots__ replaces __dict__, so dynamic attribute assignment fails.
- Not including '__weakref__' in __slots__ if you need weak references to instances.
- Defining __slots__ with a string instead of a tuple or list, which is allowed but less explicit.
Variations
- Use a list instead of a tuple for __slots__, e.g., __slots__ = ['name', 'age'].
- Add '__weakref__' to __slots__ to support weak references while keeping the memory savings.
Real-world use cases
- Storing millions of rows from a database as lightweight record objects in a data pipeline.
- Implementing value objects in a domain model where immutability and low overhead matter.
- Representing game entities or simulation particles where thousands of instances are alive.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.