__slots__ in Classes — Saving Memory
Published:
• Last updated:
• By Jeferson Peter
Python
A common scenario is building classes for data models.
By default, each instance stores attributes in a dictionary, which takes memory.
With__slots__, you can restrict attributes and reduce memory usage.
Without slots
import sys
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(sys.getsizeof(p.__dict__))
# size of underlying dict
With slots
class PersonSlots:
__slots__ = ("name", "age")
def __init__(self, name, age):
self.name = name
self.age = age
p = PersonSlots("Bob", 25)
print(hasattr(p, "__dict__"))
# False
Why use slots?
- Saves memory for large numbers of objects.
- Prevents creation of new attributes not listed.
- Slight speed improvement in attribute access.
Conclusion
Use __slots__ in performance-sensitive cases with many instances.
For general use, normal classes are more flexible.