What is a reference cycle in python?

IT Ninja picture IT Ninja · Mar 28, 2012 · Viewed 10k times · Source

I have looked in the official documentation for python, but i cannot seem to find what a reference cycle is. Could anyone please clarify what it is for me, as i am trying to understand the GC module. Thank you in advance for your replies.

Answer

Platinum Azure picture Platinum Azure · Mar 28, 2012

A reference cycle simply means one or more objects referencing each other, such that if you drew it out on paper with arrows representing the dependencies you would see a cycle.

The (almost) simplest reference cycle is having two objects a and b that refer to each other:

a.other = b
b.some_attr = a

Naive garbage collectors work strictly off of whether or not an object is referenced by another object. In this case, if both a and b are not referred to by anything else, they still refer to each other and a naive garbage collector may not reclaim the memory. (I don't know if Python can be trapped by reference cycles or not, though.)

EDIT: The simplest reference cycle is an object that refers to itself:

a = []
a.append(a)