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.

Medium Python 3.9+ Aug 9, 2026 OOP & classes 13 views 0 copies

Python code

32 lines
Python 3.9+
```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

stdout
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

  1. Use a mutable list in __slots__ if you need mutable size, but prefer a fixed tuple for most cases
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.