Sub topic 5
Reference cycles and the cyclic garbage collector
This chapter assumes you know how reference counting works in CPython: every object tracks how many references point to it, and it is freed when that count reaches zero. You should also be comfortable with classes and the gc module's basic existence.
Why reference counting is not enough
Reference counting fails when objects refer to each other. If object a holds a reference to b, and b holds one back to a, each count stays at least 1 even after your code drops every outside name. Neither count can reach zero, so neither object is freed by counting alone.
CPython adds a second mechanism, the cyclic garbage collector, to find and free these unreachable groups.
Seeing a cycle survive
The following program builds a cycle, deletes the names, and uses a weak reference as a probe. A weak reference does not keep an object alive, so it shows whether the object still exists.
import gc
import weakref
class Node:
def __init__(self):
self.other = None
gc.collect()
a, b = Node(), Node()
a.other, b.other = b, a
probe = weakref.ref(a)
del a, b
print(probe() is not None) # True: the cycle keeps both objects alive
gc.collect()
print(probe()) # None: the cyclic collector freed themThe first gc.collect() clears any earlier garbage, so the result is not affected by leftovers. After del a, b, the objects are unreachable from your program but still alive. The second gc.collect() finds the cycle and frees it.
How the collector works
The cyclic collector only tracks container objects, which are objects that can hold references to other objects, such as lists, dictionaries, and instances of classes. Plain integers and strings cannot take part in a cycle, so they are not tracked.
When a collection runs, the collector does roughly this:
- Start from the tracked objects and, for each one, subtract the references that come from other tracked objects.
- Any object whose remaining count is above zero is referenced from outside the tracked set, so it is reachable.
- Everything reachable from those objects is also kept.
- The objects left over are unreachable and are freed.
When the collector runs
You normally do not call it yourself. CPython triggers it automatically based on allocation activity. Tracked objects are split into generations: new objects start in the youngest generation, and objects that survive a collection move to an older one. Young generations are collected often, because most objects die young. Older generations are collected less often, because scanning them costs more.
Exact thresholds and the details of how generations are triggered differ between Python versions, so check the documentation for the version you use. You can inspect the current settings with gc.get_threshold().
You can also run a collection on demand:
import gc
unreachable = gc.collect()
print(unreachable) # number of unreachable objects foundgc.collect() returns the number of unreachable objects it found.
Practical points
- Cycles are normal. Parent and child links, doubly linked lists, and objects that store callbacks to themselves all create them.
- Reference counting still frees most objects immediately. The cyclic collector handles the remainder, and its freeing happens later, at a time you do not control.
- Because freeing is delayed, do not rely on a cycle's objects being released at a particular moment. If an object holds a file or a lock, release it explicitly, for example with a
withblock.
Exercise
Exercise
A program creates two objects that reference each other, then deletes both names. Reference counting alone does not free them. Why not, and what frees them?
Show answer
Each object is still referenced by the other, so neither reference count reaches zero. The cyclic garbage collector finds that the pair is unreachable from the rest of the program and frees them, either automatically or when you call gc.collect().