How to Use __slots__ in Python Classes for Memory Efficiency
Defines classes with __slots__ to prevent dynamic attribute creation and reduce memory usage, including inheritance with additional slots.
Python code
32 lines```python
class Person:
__slots__ = ("name", "age")
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def greet(self) -> str:
return f"Hi, I'm {self.name} and I'm {self.age} years old."
class Employee(Person):
__slots__ = ("role",)
def __init__(self, name: str, age: int, role: str):
super().__init__(name, age)
self.role = role
def describe(self) -> str:
return f"{self.greet()} I work as {self.role}."
if __name__ == "__main__":
alice = Person("Alice", 30)
bob = Employee("Bob", 25, "Developer")
print(alice.greet())
print(bob.describe())
print(f"Slots Person: {Person.__slots__}")
print(f"Slots Employee: {Employee.__slots__}")
print(f"Has no __dict__: {not hasattr(alice, '__dict__')}")
Output
Hi, I'm Alice and I'm 30 years old.
Hi, I'm Bob and I'm 25 years old. I work as Developer.
Slots Person: ('name', 'age')
Slots Employee: ('role',)
Has no __dict__: True
How it works
Using __slots__ declares the allowed attributes upfront, so Python allocates a fixed-size descriptor for each instead of a dynamic __dict__. This reduces memory footprint and speeds up attribute access. Inheritance works by adding the subclass's slots to the parent's, but each class must declare its own __slots__. Instances of a slotted class have no __dict__, so you cannot add new attributes at runtime. This pattern is ideal for classes with many instances, like data-heavy models.
Common mistakes
- Forgetting to include all attributes in __slots__, causing AttributeError on access
- Adding attributes dynamically to an instance, which fails because there is no __dict__
- Not overriding __slots__ in subclasses, which leads to missing attributes for the subclass
Variations
- Use a mutable list in __slots__ if you need mutable size, but prefer a fixed tuple for most cases
- Combine with dataclasses via `@dataclass(slots=True)` for automatic slot creation
Real-world use cases
- Optimizing memory when holding millions of objects in a data-intensive application.
- Defining lightweight domain models in game engines or simulations that require high performance.
- Creating immutable configuration or value objects without the overhead of a full dict.
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.