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.
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:
print("collection thresholds (gen0, gen1, gen2):", gc.get_threshold())
print("current object counts per generation:", gc.get_count())