What is a reference cycle in python?

2020-02-11 17:44发布

问题:

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.

回答1:

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)


回答2:

This is a reference cycle:

l = []
l.append(l)

The first element of l, i.e. l[0], is now a cyclic reference to l itself.



回答3:

>>> aRef = []
>>> aRef.append(aRef)
>>> print aRef
[[...]]

This creates a list object referred by a variable namedaRef. the first element in the list object is a reference to itself. In this case, the del aRef dereference aRef to the list object. However, the reference count of the list object does not decrease to zero and the list object is not garbage collected, since the list object still refers to itself. In this case, the garbage collector in Python will periodically check if such circular references exist and the interpreter will collect them. The following is an example to manually collect the space used by circular referenced objects.

>>> import gc
>>> gc.collect()
0
>>> del aRef
>>> gc.collect()
1
>>> gc.collect()
0


回答4:

>>> x=[1,2,3]
>>> x.append(x)
>>> x
[1, 2, 3, [...]]
>>> 

Now here variable x is referring to itself, this is called reference cycle.