QA
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→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?