Mastery
Mastery/Python/A. Object model, identity & memory
T2 · intermediate depth

Reference counting + generational cyclic GC

CPython's primary memory management is reference counting: an object is freed the instant its refcount hits zero -- deterministic, immediate. But reference counting alone can't free a reference cycle (two objects pointing at each other) even after nothing else refers to either one -- neither refcount ever reaches zero on its own. That's what the separate, generational cyclic garbage collector (gc module) exists for: it periodically scans for and breaks unreachable cycles.

python
import gc, weakref

class Node:
    def __init__(self):
        self.ref = None

a = Node()
b = Node()
a.ref = b
b.ref = a   # a cycle -- each keeps the other's refcount above zero

watcher = weakref.finalize(a, lambda: print("  (a was actually collected)"))
del a, b
print("right after del, before gc.collect() -- finalized yet?", not watcher.alive, "(refcounting alone can't free a cycle)")

gc.collect()
print("after an explicit gc.collect() -- finalized?", not watcher.alive)

The GC only runs a full cyclic sweep periodically, based on generation thresholds -- not on every allocation:

python
print("collection thresholds (gen0, gen1, gen2):", gc.get_threshold())
print("current object counts per generation:", gc.get_count())

Interview angle

A strong "do you understand CPython, not just Python" question: "if CPython uses reference counting, why does it also need a garbage collector?" The correct answer — cycles — shows real understanding of memory management rather than a vague "Python handles memory for you." A good follow-up is asking why reference counting alone gives Python deterministic cleanup (unlike a purely tracing-GC language), which explains why __del__ timing is predictable in CPython in ways it isn't in, say, Java.

In the industry

Reference cycles are a real, if uncommon, source of memory growth in long-running Python services — especially with objects that reference each other bidirectionally (parent/child trees, observer patterns, callback registries). The standard fixes are breaking the cycle deliberately (a weakref on the back-edge) or trusting the cyclic collector, tuning its thresholds only after profiling shows it's actually a bottleneck — premature GC tuning is a common, usually unnecessary micro-optimization.