In this lesson, you will learn how Python stores object attributes and how to control memory usage using the __dict__ and __slots__ mechanisms.
Understanding the __dict__ Attribute
By default, every Python object stores its attributes in a dictionary called __dict__. This is what makes Python classes so flexible; you can add an attribute to an object at any time (e.g., my_obj.new_attr = 10), and Python simply adds a new key-value pair to that internal dictionary.
While this dynamic nature is powerful, it carries a memory cost. Because dictionaries are optimized for fast lookups, they require a significant amount of memory for every single instance created. If you are creating millions of objects, this overhead can add up quickly.
Optimizing with __slots__
To restrict this behavior and save memory, you can use __slots__. When you define __slots__ in a class, you are explicitly telling Python which attributes the instances will have.
class EfficientPoint:
# Restrict attributes to only x and y
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
p = EfficientPoint(1, 2)
# p.z = 3 # This would raise an AttributeError!
By defining __slots__, Python no longer creates a __dict__ for each instance. Instead, it reserves a small, fixed amount of space for the specific variables listed. This significantly reduces the memory footprint of your objects and prevents the accidental creation of undefined attributes at runtime.
Trade-offs to Consider
Using __slots__ makes your objects more rigid. Since there is no __dict__, you cannot dynamically add new attributes to instances of that class. Additionally, if you use __slots__ in a parent class, you must explicitly declare __slots__ in any subclass as well, or the subclass will regain a __dict__ and negate the memory savings. Use this technique when you are certain your class structure is fixed and you need to optimize for large-scale memory efficiency.
Key Takeaway: While __dict__ provides the dynamic flexibility typical of Python objects, using __slots__ allows you to trade that flexibility for significant memory savings by explicitly declaring allowed attributes.