Python › Memory Management & Garbage Collection

What is a reference cycle, and why can't simple reference counting free it?

Intermediate

Answer

A reference cycle occurs when two or more objects reference each other (directly or indirectly), keeping their reference counts above zero even when nothing outside the cycle refers to them -- so pure reference counting never reaches zero for these objects, causing a memory leak without a separate cycle-detecting collector.
class Node:
    def __init__(self):
        self.parent = None
        self.child = None

a, b = Node(), Node()
a.child = b
b.parent = a  # cycle: a -> b -> a
del a, b  # refcounts don't reach 0 due to the cycle
Real-world example A tree data structure where each node stores both a parent and child reference forms a natural cycle that relies on the cyclic garbage collector, not refcounting, to eventually be reclaimed.

Common follow-ups: How does the generational garbage collector find cycles?;How can weakref break such cycles intentionally?