Back
+15 XP
Concept

Memory Optimization with `__slots__`

By default, every Python instance stores attributes in a dynamic `__dict__` hash map. `__slots__` eliminates `__dict__`, reducing RAM consumption by up to 50%.

python
class FastNode:
    __slots__ = ("x", "y")  # Fixed attributes only!
    def __init__(self, x, y):
        self.x = x
        self.y = y

n = FastNode(1, 2)
# n.z = 3  # AttributeError!
print(n.x, n.y)

# 8. Memory Optimization with `__slots__` By default, every Python instance stores attributes in a dynamic `__dict__` hash map. `__slots__` eliminates `__dict__`, reducing RAM consumption by up to 50%: ```python class FastNode: __slots__ = ("x", "y") # Fixed attributes only! def __init__(self, x, y): self.x = x self.y = y n = FastNode(1, 2) # n.z = 3 # AttributeError! print(n.x, n.y) ``` When building high-throughput systems that hold millions of in-memory objects (like graph nodes or game entities), using `__slots__` drastically prevents out-of-memory crashes.

Checkpoint

What does defining `__slots__` remove from instances to save memory?

Practice

Create a class `Pixel` with `__slots__ = ("r", "g", "b")`. Initialize `p = Pixel(255, 0, 0)` by assigning `r, g, b` in `__init__`. Print `p.r`.

Terminal
01
Tap code blocks below to assemble
Available Blocks