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: