Python’s Cyclic Garbage Collector
Python’s cyclic garbage collector is the part of CPython that finds groups of objects that still reference one another but can no longer be reached by running code. It complements reference counting, which normally frees an object as soon as its reference count reaches zero.
The problem reference counting cannot solve
In CPython, every object has a reference count: the number of references currently pointing to it. When the count reaches zero, CPython can usually destroy the object immediately.
That works well for ordinary objects, but not for a cycle:
class Node:
def __init__(self):
self.other = None
first = Node()
second = Node()
first.other = second
second.other = first
del first
del second
After the del statements, the two Node objects still point at each other. Each has a reference count of one, even though no live variable can reach either object. Reference counting alone sees references, not whether those references lead back to useful program state.
Without another mechanism, every such cycle would remain allocated until the process ended. Long-running services could steadily retain memory through abandoned object graphs.
The cyclic collector exists to answer a different question from reference counting: not “does anything point to this object?” but “can running code still get to this object?”
What the collector tracks
The cycle detector does not need to inspect every Python object. It mainly tracks container objects: objects that can hold references to other objects, such as lists, dictionaries, sets, and instances with attributes. An integer or a plain string cannot contain a reference back to another object, so it cannot participate in a reference cycle by itself.
CPython maintains bookkeeping for tracked containers in addition to their normal reference counts. Some containers can be temporarily or permanently left out of this tracking when their contents cannot form a cycle—for example, certain tuples containing only non-container values. The exact tracking details are an implementation optimization, not a promise made by the Python language in general.
This is why the phrase “Python’s garbage collector” usually needs qualification. The mechanism described here is CPython’s cyclic garbage collector. Other Python implementations may use different memory-management strategies.
How a collection finds a cycle
A collection starts with a selected set of tracked containers. Conceptually, CPython performs these steps:
- Build a candidate set. The collector examines objects in one or more age groups, called generations.
- Estimate outside references. For each candidate, it starts with the object’s reference count and subtracts references coming from other candidates in the set. Those internal references keep a cycle alive numerically, but they do not prove that anything outside the set can reach it.
- Follow externally reachable objects. Candidates with references from outside the candidate set are considered reachable. The collector follows their references and marks other candidates they can reach as reachable too.
- Identify the remainder. Candidates not reachable from outside are an unreachable cycle, even if their members still point at one another.
- Finalize and release them. CPython clears or disposes of the unreachable objects according to its object-finalization rules, releasing their references so the objects can be reclaimed.
This is a reachability analysis, but it does not require tracing the entire process heap on every collection. The collector limits the work to tracked candidates, then uses the result to handle cycles that reference counting cannot break.
Objects with finalizers—typically a user-defined __del__ method—add complications because destroying an object may run arbitrary Python code. Modern CPython can safely finalize many cyclic structures, but finalizers can still delay reclamation or resurrect objects by storing them somewhere reachable. Code that relies on prompt cleanup should use an explicit context manager or close()-style operation instead of waiting for garbage collection.
Why collections are generational
New objects are more likely to become temporary than long-lived objects. The collector uses that observation to avoid repeatedly examining old, stable object graphs.
CPython organizes tracked objects by age. A newly tracked object is collected frequently. If it survives, it is promoted to an older generation and examined less often. A collection of an older generation also considers younger objects, because a cycle can include objects of different ages.
The gc module exposes controls such as gc.get_threshold(), gc.set_threshold(), and gc.collect(). Thresholds determine when automatic collections are triggered based on allocation and deallocation activity. Their precise generation layout and tuning rules have changed across CPython releases; current versions should be checked against the version being operated. The enduring idea is stable: collect young objects often, and spend less work revisiting survivors.
What this means for memory behavior
A cycle is not necessarily a memory leak. If the cyclic collector runs and the objects have no external path to them, the cycle can be reclaimed. A leak is more often a graph that remains reachable accidentally—for example, an unbounded cache, a global list of request objects, or a callback registry that never unregisters handlers. The cyclic collector correctly leaves those objects alone.
Collection is also not the same as returning memory to the operating system. CPython’s object allocator commonly keeps freed memory in process-level pools so it can satisfy later allocations quickly. Consequently, gc.collect() may reduce the number of live Python objects without making a resident-memory graph or operating-system RSS measurement fall immediately.
You may encounter this mechanism in messages such as “gc: collecting generation,” in memory investigations involving gc.collect(), or in tuning discussions about gc.set_threshold(). Those controls can help diagnose or reduce collection overhead, but they do not replace ownership design. Break unnecessary links, bound caches, unregister callbacks, and release external resources explicitly. The cyclic collector is a safety net for unreachable object cycles—not a general solution for objects that the program still keeps reachable.