0Pricing
Python Academy · Lesson

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 them

The 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

  1. CPython Reference Counting
  2. The Garbage Collector and Cyclic References
  3. Profiling with cProfile and line_profiler
  4. Memory Profiling with tracemalloc
← Back to Python Academy