Collect Unreachable Cycles
Core idea
Reference counting alone cannot reclaim a cycle of objects that refer to each other. CPython supplements it with a cyclic collector for tracked containers. A cycle reachable through a live root is not garbage. gc.collect requests a collection; its result includes unrelated objects, so observe the specific object rather than an exact global count.
import gc, weakrefclass Node: passx=Node(); x.link=xr=weakref.ref(x)gc.collect()print(r() is x)A live binding keeps the cycle reachable.
Expected output:
TrueCollect an unreachable cycle
import gc, weakrefclass Node: passwas=gc.isenabled(); gc.disable()try: x=Node(); x.link=x r=weakref.ref(x); del x print(r() is not None) gc.collect() print(r() is None)finally: if was: gc.enable()With automatic cycle collection disabled, explicit collection reclaims this ordinary cycle on the tested CPython build.
Expected output:
TrueTrueCommon mistake
Disabling gc does not disable reference counting. Avoid global collector changes in shared applications; the fixture restores the prior enabled state.
Practice
Create two nodes pointing to each other; retain one in a list, then remove that root and compare weak references after collection.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cycles and garbage collection
Check your understanding of cycles and garbage collection.
What is printed?
import gcprint(gc.is_tracked([]))What is printed?
import gcx=[]; x.append(x)gc.collect()print(x[0] is x)Why can reference counting alone miss a cycle?
What does gc.disable stop?