Intermediate LevelPython
How does defining __slots__ = ("name", "age") reduce RAM consumption by suppressing per-instance __dict__ creation?
❓ Interview Prompt: Explain `__slots__`, suppressing `__dict__` dynamic dictionary creation, fixed C array memory layout, and 60% RAM savings.
By default, every Python class instance allocates a dynamic dictionary '__dict__' consuming ~400+ bytes of RAM to support dynamic attribute additions.
The '__slots__' Optimization:
Defining '__slots__ = ('name', 'age')' suppresses '__dict__' creation, storing attributes in a fixed-size C array:
•
Reduces per-instance RAM memory consumption by 60% when instantiating millions of objects!
Code Implementation Example
python
import sys
class StandardUser:
def __init__(self, name, age):
self.name = name
self.age = age
class SlottedUser:
__slots__ = ('name', 'age') # Suppresses __dict__ creation!
def __init__(self, name, age):
self.name = name
self.age = age
u1 = StandardUser('Alice', 30)
u2 = SlottedUser('Alice', 30)
print('Standard RAM:', sys.getsizeof(u1.__dict__)) # ~104+ bytes dict
# u2 has no __dict__, consuming minimal C memory!💡Reducing instance memory overhead using __slots__.
🎯 Interview Key Takeaway
Define __slots__ on classes instantiated millions of times to reduce RAM footprint by 60%.
#__slots__#Memory Optimization#Performance#Intermediate
Back to all Python Questions→