Sub topic 3
Reducing Memory Use in CPython
This chapter assumes basic Python syntax, classes, collections, and running CPython scripts. It focuses on practical ways to reduce memory use and investigate objects that remain alive unexpectedly.
Reducing per-instance memory with `__slots__`
A normal instance usually stores attributes in a __dict__, a dictionary that maps attribute names to values. That dictionary adds overhead for every instance. __slots__ declares a fixed set of attributes and removes the instance dictionary by default.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
points = [Point(i, i * 2) for i in range(1_000)]
print(points[0].x)__slots__ can reduce memory when a program creates many small, similarly shaped objects. It also prevents adding undeclared attributes. However, it can complicate inheritance and weak references. Use it after measuring a real memory problem.
Avoiding large allocations with generators
A list comprehension creates and stores every result. A generator expression produces one result at a time.
total = sum(n * n for n in range(1_000_000))
print(total)This avoids storing one million squares at once. The trade-off is that a generator is single-use and usually cannot provide random access.
Finding allocations with `tracemalloc`
tracemalloc records Python memory allocations and their source locations.
import tracemalloc
tracemalloc.start()
data = [str(i) for i in range(100_000)]
snapshot = tracemalloc.take_snapshot()
for statistic in snapshot.statistics("lineno")[:3]:
print(stat)Compare two snapshots before and after an operation to find which lines increased memory use. tracemalloc tracks Python allocations, not all native memory used by extension modules.
Common memory leak patterns and fixes
In Python, a leak often means an unwanted reference keeps an object reachable.
- A global list grows forever. Remove old entries or bound its size.
- A cache has no eviction policy. Use a bounded cache.
- Callbacks or event handlers retain objects. Unregister them.
- A closure captures a large object. Avoid unnecessary captures.
- A reference cycle delays cleanup. Break the cycle or let the cyclic collector handle it.
Inspecting and tuning the garbage collector
Reference counting frees most objects as soon as their last strong reference disappears. The cyclic garbage collector finds unreachable cycles.
import gc
print(gc.get_count())
print(gc.get_threshold())
unreachable = gc.collect()
print("collected:", unreachable)
gc.set_threshold(700, 10, 10)Tune thresholds only after profiling. Frequent collections add overhead, while infrequent collections retain cyclic garbage longer. Do not call gc.collect() routinely as a substitute for fixing unwanted references.
Exercise
When is a generator a better choice than a list?
Show answer
Use a generator when results can be processed once and do not all need to remain in memory.