Garbage Collector for Reference Cycles

suggest change

The only time the garbage collector is needed is if you have a reference cycle. The simplest example of a reference cycle is one in which A refers to B and B refers to A, while nothing else refers to either A or B. Neither A nor B is accessible from anywhere in the program, so they can safely be destructed, yet their reference counts are 1 and so they cannot be freed by the reference counting algorithm alone.

>>> import gc; gc.disable()  # disable garbage collector
>>> class Track:
...     def __init__(self):
...         print("Initialized")
...     def __del__(self):
...         print("Destructed")
...
>>> A = Track()
Initialized
>>> B = Track()
Initialized
>>> A.other = B
>>> B.other = A
>>> del A; del B  # objects are not destructed due to reference cycle
>>> gc.collect()  # trigger collection
Destructed
Destructed
2

A reference cycle can be arbitrarily long. If A points to B points to C points to … points to Z which points to A, then none of A through Z will be collected, until the garbage collection phase:

>>> objs = [Track() for _ in range(10)]
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
Initialized
>>> for i in range(len(objs)-1):
...     objs[i].other = objs[i + 1]
...
>>> objs[-1].other = objs[0]  # complete the cycle
>>> del objs                  # no one can refer to objs now - still not destructed
>>> gc.collect()
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
Destructed
10

In a fresh 3.14 process those gc.collect() calls returned 2 and 10, one per Track. Other unreachable objects make the number larger. The old transcripts showed 4 and 20. The Destructed lines are printed by gc.collect() before it returns.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents