Sub topic 5
Reference cycles and the cyclic garbage collector
This chapter assumes you know how reference counting frees objects (the previous chapter), and that you can read basic Python classes and use the gc and weakref modules at a simple level. It covers why reference counting cannot free every object, how CPython's cyclic collector finds the rest, and which mistakes cause cycles to linger.
Why reference counting is not enough
Reference counting frees an object when its count reaches zero. A cycle prevents that. If object a refers to b and b refers to a, each holds the other's count above zero, even when no name in your program can reach either one.
import gc
import weakref
class Node:
def __init__(self):
self.other = None
gc.disable() # stop automatic collection so the result is predictable
a, b = Node(), Node()
a.other, b.other = b, a # a cycle: a -> b -> a
probe = weakref.ref(a)
del a, b # no names remain, but each object still has one reference
print(probe() is not None) # True: the cycle keeps both alive
gc.collect()
print(probe()) # None: the cyclic collector freed them
gc.enable()The weak reference probe lets you observe the object without keeping it alive. Both objects were unreachable after del, yet they stayed in memory until gc.collect() ran.
A self-reference is the smallest cycle. A list that contains itself (x = []; x.append(x)) has a count that never reaches zero by del x alone.
What the collector tracks
The cyclic collector only examines container objects. These are objects that can hold references to other objects: lists, dicts, sets, instances of user-defined classes, and so on. Objects that cannot hold references, such as int, float, and str, cannot be part of a cycle and are never tracked. You can check this with gc.is_tracked():
import gc
print(gc.is_tracked("text")) # False
print(gc.is_tracked(42)) # False
print(gc.is_tracked([])) # TrueCPython also skips some containers it can prove are harmless. A tuple holding only atomic values may be untracked after its first collection pass. You should not rely on this detail, but it explains why gc.get_objects() shows fewer objects than you might expect.
How the collector finds unreachable cycles
The collector does not trace from your program's roots. It works only on the set of tracked objects in the generation being collected, using the reference counts that already exist.
- For every object in the set, copy its reference count into a scratch field,
gc_refs. - For every object in the set, visit the objects it refers to and decrement their
gc_refs. This removes references that come from inside the set. - Any object whose
gc_refsis still above zero is referenced from outside the set (a variable, a stack frame, an older generation). It is reachable. - Everything reachable from those objects is also marked reachable.
- The objects left over are unreachable. Only cycles, and objects hanging off cycles, can be in this group.
- The collector runs finalizers, clears weak references to these objects, and then breaks the cycles (it clears each object's references) so that reference counting frees them.
Because step 2 uses subtraction rather than a full graph walk from the roots, a collection of a small generation does not need to scan the whole heap.
Generations and when collection runs
CPython assumes that most objects die young. It groups tracked containers into generations and collects the youngest group most often. In versions up to 3.13 there are three generations, numbered 0, 1, and 2. The incremental collector introduced in 3.14 changed the layout (two generations, with the old one collected in increments), so check your version's gc documentation for the details of tuning.
For the three-generation design, the rules are:
- Each new tracked container goes into generation 0.
- Generation 0 is collected when allocations minus deallocations of tracked containers exceed
threshold0(700 by default). - Survivors move to the next generation. Generation 1 is collected after generation 0 has been collected more than
threshold1times (default 10). Generation 2 follows the same rule withthreshold2. - A full collection of generation 2 has an extra condition: the number of objects that survived into it since the last full run must exceed about a quarter of its size. This prevents a program with a large, stable heap from paying for a full scan too often.
You can inspect these values at runtime:
import gc
print(gc.get_threshold()) # (700, 10, 10) by default in 3.12 and earlier
print(gc.get_count()) # current counters, for example (312, 4, 2)
print(gc.get_stats()) # per-generation totals: collections, collected, uncollectable| Function | What it does |
|---|---|
| `gc.collect(generation=2)` | Runs a collection now and returns the number of unreachable objects found |
| `gc.get_threshold()` / `gc.set_threshold()` | Reads or changes the trigger values |
| `gc.get_count()` | Returns the current counters for each generation |
| `gc.disable()` / `gc.enable()` | Turns automatic collection off or on. Reference counting is unaffected |
| `gc.get_stats()` | Returns cumulative statistics for each generation |
| `gc.callbacks` | A list of functions called before and after every collection |
Tuning thresholds is covered in its own chapter. Here, the point is that automatic collection is triggered by allocation activity, not by a timer and not by memory pressure.
Watching the collector work
The gc.callbacks list lets you observe each pass. A callback receives a phase ("start" or "stop") and an info dictionary.
import gc
class Tracked:
def __init__(self, name):
self.name = name
self.peer = None
def __del__(self):
print("finalized", self.name)
def report(phase, info):
if phase == "stop":
print("generation", info["generation"],
"collected", info["collected"],
"uncollectable", info["uncollectable"])
gc.callbacks.append(report)
a, b = Tracked("a"), Tracked("b")
a.peer, b.peer = b, a
del a, b
gc.collect()
gc.callbacks.remove(report)The output shows both finalizers running during the collection, in an unspecified order, followed by a report line. The collected count is at least 2 and may be larger, because the instances' attribute dictionaries can be counted separately in some versions.
Finalizers and cycles
Before Python 3.4, an object with a __del__ method in a cycle could not be collected safely, because the collector did not know which finalizer to run first. Such objects were moved to gc.garbage and stayed there. PEP 442 removed this restriction. Today the collector calls __del__ on each object in the cycle once and then frees them, as the example above shows.
Two details remain relevant:
- A finalizer can resurrect an object by storing
selfsomewhere reachable. The collector detects this and keeps the object, but__del__is not called a second time for it. - Objects from C extensions that do not implement the required hooks can still end up in
gc.garbage. In ordinary Python code, a non-emptygc.garbageis rare, and it is worth investigating when it happens.
Common errors
- Believing
delfrees the object.del xremoves one name. The object survives while any other reference exists, including references from a cycle. - Disabling the collector for speed and forgetting the cycles.
gc.disable()is safe only if your code creates no cycles. Frameworks, exception tracebacks stored in variables, and parent/child object trees all create cycles easily. - Calling
gc.collect()in a tight loop. A full collection scans every tracked object. Calling it frequently often costs more than it saves. Call it at natural boundaries, such as after processing a large batch. - Expecting memory to return to the operating system. Collecting a cycle frees the objects to Python's allocator. The process's resident memory may not shrink, because the allocator keeps freed blocks for reuse.
- Using
gc.get_objects()in production. It returns a list of every tracked object. That list is large and itself holds references, which can distort what you are trying to measure. - Breaking a cycle with a strong back-reference. A child that stores a
parentattribute creates a cycle. When the child does not need to keep its parent alive, storeweakref.ref(parent)instead.
Choosing between a cycle and a weak reference
Cycles are not wrong, and the collector exists to handle them. A tree where children point to parents is simple to write and the collector frees it correctly. The cost is delay: the memory remains until a collection of the right generation runs, and an object that survived long enough to reach generation 2 may wait a long time. Use a weak back-reference when you need prompt release, when the objects are large, or when they hold external resources. Otherwise, a plain cycle is acceptable.
Exercise
A program creates one million small Node objects, each part of a two-object cycle, and then deletes every name that refers to them. It has called gc.disable() at startup. Memory use stays high after the deletion. What is the cause, and what are two ways to fix it?
Show answer
With the collector disabled, nothing breaks the cycles. Reference counting alone cannot free them, because each object still holds the other's count above zero. One fix is to call gc.collect() after the deletion (or re-enable the collector with gc.enable()). The other is to remove the cycle by making one direction a weak reference with weakref.ref, so that reference counting frees each object as soon as the last strong reference disappears.
Exercise
In the collection algorithm, why is an object whose gc_refs is still above zero after the subtraction step treated as reachable?
Show answer
The subtraction removes only the references that come from other objects inside the set being collected. A remaining positive count means something outside the set refers to the object, such as a variable, a stack frame, or an object in an older generation. That outside reference may be live, so the collector must keep the object and everything it refers to.