__slots__ in Python: What It Is and When to Use It
__slots__ is a special attribute in Python classes that limits the attributes an instance can have, saving memory by avoiding the creation of a dynamic dictionary for each object. It helps make objects smaller and faster by fixing the allowed attributes at class creation.How It Works
Normally, Python stores an object's attributes in a dictionary called __dict__. This dictionary allows you to add or change attributes freely, like a flexible toolbox. But this flexibility uses extra memory for each object.
When you define __slots__ in a class, you tell Python exactly which attributes the objects of that class can have. This is like giving each object a fixed set of labeled boxes instead of a big toolbox. Because Python knows the exact attributes ahead of time, it doesn't need to create a dictionary for each object, saving memory and sometimes making attribute access faster.
Example
__slots__. The class with __slots__ only allows the attributes listed and uses less memory.class PersonWithoutSlots: def __init__(self, name, age): self.name = name self.age = age class PersonWithSlots: __slots__ = ['name', 'age'] def __init__(self, name, age): self.name = name self.age = age p1 = PersonWithoutSlots('Alice', 30) p2 = PersonWithSlots('Bob', 25) print(hasattr(p1, '__dict__')) # True print(hasattr(p2, '__dict__')) # False # Trying to add a new attribute not in __slots__ raises an error try: p2.height = 170 except AttributeError as e: print(e)
When to Use
Use __slots__ when you create many instances of a class and want to save memory. This is common in programs that handle large data sets or many objects, like games, simulations, or data processing.
However, __slots__ restricts flexibility: you cannot add new attributes not listed in __slots__, and some Python features like multiple inheritance can be tricky with it. So use it when memory is important and your class design is stable.
Key Points
__slots__saves memory by preventing the creation of__dict__for each instance.- It fixes the set of allowed attributes, disallowing new ones.
- It can make attribute access slightly faster.
- It is best for classes with many instances and stable attribute sets.
- It limits flexibility and can complicate inheritance.
Key Takeaways
__slots__ reduces memory use by fixing allowed attributes in a class.__slots__ if you need flexible or complex class designs.