Course contentsShow
← Python
Lesson 466 of 1,0607. Object-Oriented ProgrammingFree lesson

Optimizing Memory Usage with Slots

Understand how the __slots__ attribute prevents the creation of instance dictionaries to significantly reduce memory footprint for large object collections.

In this lesson, you will learn how to drastically reduce the memory footprint of your Python objects using the __slots__ attribute.

The Hidden Cost of Dictionaries

By default, every instance of a standard Python class stores its attributes in a special dictionary called __dict__. This dictionary is highly flexible; it allows you to add new attributes to an object dynamically at runtime (e.g., my_obj.new_attr = 10).

However, this flexibility comes at a cost: dictionaries are memory-intensive hash tables. If you create thousands or millions of instances of a simple class, those individual dictionaries add up to a significant amount of RAM usage.

Introducing __slots__

When you know your class structure is fixed and you don't need to add new attributes on the fly, you can use __slots__. By defining __slots__, you instruct Python to allocate space for a fixed set of attributes rather than creating a __dict__ for each instance.

Here is how you implement it:

class Point:
    # Explicitly define the allowed attributes
    __slots__ = ('x', 'y')

    def __init__(self, x, y):
        self.x = x
        self.y = y

# Trying to add a new attribute will now raise an AttributeError
# p = Point(1, 2)
# p.z = 3  # This will fail!

Why it Matters

Because the object no longer has a __dict__, Python stores the attributes in a compact array-like structure. This removes the overhead of the hash table, leading to much smaller memory usage for large collections of objects.

You should consider using __slots__ specifically when:

  1. You are creating a very large number of instances (thousands or more).
  2. Your class is relatively simple and does not require dynamic attribute assignment.
  3. You want to enforce a strict structure on your objects to prevent accidental attribute creation.

Key Takeaway: By defining __slots__, you replace the memory-heavy per-instance dictionary with a fixed-size storage structure, allowing you to manage massive collections of objects more efficiently.