The Garbage Collector and Cyclic References
Learn how the gc module handles reference cycles.
Why Reference Counting Is Not Enough
Reference counting cannot collect objects involved in reference cycles — each holds a reference to the other, so neither count drops to 0.
# Reference cycle: a → b → a
a = {}
b = {"other": a}
a["other"] = b
del a, b
# Both objects are unreachable but refcount > 0
# Only the cyclic GC can collect themThe gc Module
gc is the cyclic garbage collector. It periodically scans tracked objects for unreachable cycles and collects them.
import gc
gc.collect() # trigger immediately
print(gc.garbage) # objects with __del__ in cycles (cannot auto-collect)All lessons in this course
- CPython Reference Counting
- The Garbage Collector and Cyclic References
- Profiling with cProfile and line_profiler
- Memory Profiling with tracemalloc