6.6 Garbage Collection
How CPython's reference-counting memory manager works, why a supplementary cyclic garbage collector exists for reference cycles, and how to use del and the gc module.
Reference Counting
What Is It?
CPython’s primary memory-management mechanism, introduced in 5.12 Memory Representation — every object tracks how many references point to it, incrementing on each new reference and decrementing when one goes away.
Why Is It Used?
As soon as this count hits zero, the object’s memory is freed immediately, without waiting for a periodic sweep — unlike garbage collectors in some other languages.
>>> import sys
>>> x = [1, 2, 3]
>>> sys.getrefcount(x) # includes the temporary reference getrefcount's own call creates
2
The Cyclic Garbage Collector
What Is It?
A supplementary mechanism that specifically detects and cleans up reference cycles — e.g. two objects that reference each other — which reference counting alone can never resolve, since each one’s count never naturally reaches zero.
>>> import gc
>>> gc.isenabled()
True
>>> gc.collect() # force a collection pass; returns count of objects collected
0
del and Memory Cleanup
del removes a name’s reference to an object (see also 6.9 Lifetime of Variables); if that was the last reference, the object becomes eligible for immediate cleanup via reference counting.
>>> y = [1, 2, 3]
>>> del y
>>> y
Traceback (most recent call last):
NameError: name 'y' is not defined
Quick Interview Answer
“CPython frees memory through two mechanisms working together. Reference counting is primary: every object tracks how many references point to it, and it’s freed the instant that count hits zero — no waiting for a sweep. That alone can’t free reference cycles, like two objects pointing at each other, since neither’s count ever naturally reaches zero — so a supplementary cyclic garbage collector, exposed through the
gcmodule, periodically scans for and cleans up exactly that case.deljust removes one name’s reference; the object is only actually freed once its refcount reaches zero.”
Common Mistakes
- Believing Python has no garbage collector because reference counting handles most cases — the cyclic collector is a real, necessary second mechanism for reference cycles.
- Thinking
del ximmediately destroys the object — it only removes that one reference; the object survives if anything else still references it. - Calling
gc.collect()routinely in application code “just in case” — it’s rarely needed outside of debugging memory issues or specific long-running-process tuning.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form