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.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 12 views 0 copies

Python code

16 lines
Python 3.9+
class 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

stdout
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

  1. Use a list instead of a tuple for __slots__, e.g., __slots__ = ['name', 'age'].
  2. 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

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.