Skip to content

Lesson 20 of 20 · 17m

Memory in CPython: Refcounts, Cycles, and Measuring Before You Guess

CPython frees by refcount and chases cycles with the gc collector; __slots__, gc.freeze(), and tracemalloc are the tools that matter before you optimize.

del x doesn't free memory. It removes one reference — and CPython frees the object when the count of references reaches zero, immediately and deterministically. There is no mark-and-sweep pause for ordinary garbage; the object's memory goes back the moment the last name drops. sys.getrefcount(x) always reads one higher than you expect — the call itself holds a reference.

The cyclic collector

Refcounting cannot kill a cycle: a.b = b; b.a = a keeps both alive at refcount 1 forever. The gc module is the second collector — a generational walker that periodically traverses containers looking for unreachable cycles. Three generations, default thresholds gc.get_threshold() == (700, 10, 10): 700 allocation-deallocation deltas trigger a gen-0 pass, ten gen-0 passes trigger gen-1, ten gen-1s trigger gen-2. gc.disable() turns it off; gc.freeze() moves every live object into a permanent generation so collection never walks them.

The prefork trick is shipped, not theoretical: Instagram published "Dismissing Python Garbage Collection at Instagram" in 2017 — disable gc in uWSGI workers and, because fork is copy-on-write, memory shared at fork time stays shared; they reported roughly 10% RSS savings per worker. gc.freeze() (3.7) exists because of that work: freeze before forking and the collector's bookkeeping never dirties the shared pages. gunicorn and uvicorn prefork workers are the same shape.

One historical receipt: before PEP 442 (3.4), an object with __del__ inside a reference cycle was uncollectable — the collector couldn't pick a safe __del__ order, so it quarantined the whole cycle in gc.garbage and leaked it. PEP 442 fixed finalization ordering; gc.garbage still exists, mostly empty now. And weakref.finalize(obj, fn) is the modern cleanup that __del__ always wanted to be — __del__ can run at interpreter shutdown with globals already torn down; finalize callbacks don't have that problem.

__slots__: delete the dict

Every instance carries a __dict__ — a million small objects means a million hash tables. __slots__ = ("x", "y") replaces the dict with fixed slots; on small objects the saving is on the order of half the per-instance footprint. The costs are real: no arbitrary attributes, no weakref unless you add "__weakref__" to the slots, and functools.cached_property can't write its cache without "__dict__" in the list. A parent class that forgot __slots__ silently re-adds __dict__ to every subclass — one sloppy base defeats the whole chain.

Measure, don't guess

sys.getsizeof(x) is shallow — a list reports the list, not its contents. tracemalloc is the stdlib answer: tracemalloc.start(), snap = tracemalloc.take_snapshot(), snap.statistics("lineno") ranks allocations by line, and snap.compare_to(before, "lineno") diffs two snapshots. That finds allocators — growth, which is what a leak actually is — not garbage. objgraph.show_most_common_types() and pympler.asizeof are the third-party heavyweights.

The traps that survive review

is is identity: id() is the object's address, and CPython interns small ints (-5 through 256) and identifier-like strings, so a is "done" works until it doesn't — the correct singleton check is is None, the correct value check is ==. sys.intern exists for the legitimate version. The mutable default — def f(acc=[]) — creates one list at def time shared by every call forever; acc=None then assign inside. weakref.WeakValueDictionary is the cache that doesn't pin: entries die with their referents, the correct answer to "cache it but don't leak it". And id() gets reused after GC, which makes id()-keyed maps a bug class of their own.

The practice

Refcounts do the work; gc handles the cycles — gc.freeze() before prefork forks. __slots__ when the instance count is in the millions. tracemalloc before gc.collect() superstition. == for values, is only for None and sentinels. Mutable defaults are shared state wearing the signature of a default.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.