Cyclic GC
The cyclic garbage collector finds groups of objects that reference each other and are otherwise unreachable, so reference counts never hit zero. CPython runs it in generations on allocation thresholds.
Detailed Explanation
Reference counting frees a tree of objects from the leaves up. It cannot free a ring. Two dicts that store each other, a doubly-linked list, a parent and child that each hold a callback to the other — the counts stay at least 1.
The cyclic collector computes, for objects it tracks, whether they are reachable from outside the candidate set. If a group's only references are internal, the group is garbage. Containers (list, dict, instances with __dict__) are tracked. Many immutables are not, because they cannot participate in a new cycle.
Generations reduce cost. Generation 0 is collected often. Objects that survive move to generation 1, then 2. A full collect scans everything. Thresholds count allocations minus deallocations; they are heuristics, not promises of a schedule.
Finalisers complicate this. An object with __del__ in a cycle cannot always be collected safely, because __del__ might resurrect a neighbour. Modern CPython is better than 2.x at this, and the rule remains: do not write __del__. Use weakref.finalize or a context manager.
gc.garbage holds uncollectable objects when debug flags are on. If you see your classes there, break the cycle (weakref the back-pointer) or remove the finaliser.
You can break cycles yourself: child.parent = None in a close method, or a weakref from child to parent. Explicit teardown is clearer than waiting for a generation 2 collect in a long-running server.
gc.is_tracked(obj) tells you whether the collector cares. A small int is not tracked. A list is.
Code Examples
import gc
import weakref
class Node:
def __init__(self, name: str):
self.name = name
self.child = None
self.parent = None
parent = Node("p")
child = Node("c")
parent.child = child
child.parent = parent # cycle
probe = weakref.ref(parent)
del parent, child
gc.collect()
print(probe() is None) # True, cycle collected# Better: the back-pointer is weak, so no cycle.
class Tree:
def __init__(self, name: str, parent=None):
self.name = name
self._parent = weakref.ref(parent) if parent is not None else None
self.children = []
@property
def parent(self):
return self._parent() if self._parent is not None else NoneCommon Gotchas
Relying on cyclic GC to close sockets
it may run late or not at all if the objects are still reachable from a cache. Close explicitly.
`__del__` in a cycle
you can leak. Use `weakref.finalize`.
Tuning thresholds blindly
too-low thresholds spend CPU in collections; too-high delays reclaim. Measure RSS first.
Not every object is tracked
cycles through untracked objects are not a thing, because they cannot create new references.