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.

Worked 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:

Lesson test

Take an 8-question test on “Performance & __slots__” — concepts, output prediction, bug spotting and interview questions.