"How Does Python Garbage Collection Work? The Full Picture"
"Most explanations of how Python garbage collection works stop at reference counting and a Node cycle. This guide goes further: why `del` never frees memory, cycles hiding in callbacks and closures, and how to tune the gc module for long-running services — all with runnable experiments."
Last updated: 2026-10-05 Ask how does Python garbage collection work and you'll get the same textbook answer everywhere: reference counting plus a generational collector for cycles. It's not wrong — it's just incomplete in exactly the ways that cost you. It doesn't tell you that del never frees memory, that refcounting runs on every assignment you write, or that the cycles eating your long-running service hide in callback lists and closures, not in textbook Node toys. This guide runs the experiments the textbooks skip. What you'll learn How reference counting reclaims objects the instant their count hits zero Why del deletes a name, not memory — the refcount ladder proves it The generational collector: generations 0, 1, 2 and the threshold math Real-world cycle patterns that leak in backends: callbacks, closures, observers The gc module: collect() , disable() , set_threshold() and their costs Why __del__ is unreliable in cycles — and what to use instead Leak-hunting with gc.DEBUG_LEAK in five minutes When to tune the collector and when to leave it alone How does Python garbage collection work? The two collectors, explained Python runs two memory managers. The first is reference counting : every object carries a count of references pointing at it. When the count hits zero, the object is freed *immediately* — no sweep, no pause. This handles the vast majority of objects. The second is the cyclic (generational) collector behind the gc module. Refcounting's blind spot is cycles: A → B → A keeps both counts above zero forever. The cyclic collector periodically walks the object graph for these unreachable islands, organized into three generations (0, 1, 2) — young objects scanned often, old survivors rarely. Mental model: refcounting is the…