What is a reference cycle in python?

后端 未结 4 963
灰色年华
灰色年华 2020-12-18 17:57

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

4条回答
  •  遥遥无期
    2020-12-18 18:36

    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)
    

提交回复
热议问题