← Back to Python

The Subtle Power of __slots__ in Python Classes

1

By default, Python classes are dynamic — you can add new attributes to objects at any time. This flexibility is great, but it comes at a cost: every object stores its attributes in a special dictionary called __dict__. For programs with many objects, this dictionary storage can use a lot of memory.

That’s where __slots__ comes in. By defining __slots__ in your class, you tell Python exactly which attributes the class will have. This removes the need for __dict__ and can:

  • Reduce memory usage — especially for large numbers of objects.
  • Make attribute access slightly faster.
  • Prevent accidental creation of new, misspelled attributes.

Here’s an example:

class Point:
    __slots__ = ('x', 'y')  # Only allow these two attributes
    
    def __init__(self, x, y):
        self.x = x
        self.y = y

Now, every Point object can only have x and y. No extra attributes are allowed, and the memory footprint is smaller.

When to Use __slots__

Use __slots__ when:

  • You’ll be creating many instances of a class.
  • You know exactly which attributes the class will have.
  • You want to prevent adding unexpected attributes.

If you need the flexibility of dynamic attributes or your class will be subclassed, it’s better to skip __slots__. But for performance-sensitive code, this simple change can make a big difference.

0 Comments

Anonymous comments may require approval before they appear.

  • No comments yet.