L6Β·Expert

πŸš€Performance & __slots__

Profiling, __slots__, and when to reach for C.

performanceprofile__slots__cython

Β§ 1Measure first

cProfile, timeit, and py-spy. Don't optimize before you profile.

Β§ 2__slots__

Declaring __slots__ on a class skips __dict__ per instance β€” significant memory savings when you have millions of instances.

Β§ 3Reach for C

NumPy for numeric arrays. Cython, mypyc, or Rust extensions (via PyO3) when pure-Python is a bottleneck.

Example

1class Point:​
2 __slots__ = ("x", "y")​
3 def __init__(self, x, y):​
4 self.x, self.y = x, y​
5​
6p = Point(3, 4)​
7print(p.x, p.y)​
8try:​
9 p.z = 5 # AttributeError β€” no __dict__​
10except AttributeError as e:​
11 print("blocked:", e)​

Try it live Β· Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
__slots__ mainly saves:
Prev
Memory, References & gc