Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a reference cycle in python?

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.

like image 673
IT Ninja Avatar asked Mar 28 '12 15:03

IT Ninja


People also ask

What is a reference count in Python?

Reference counting is one of the memory management technique in which the objects are deallocated when there is no reference to them in a program. Let's try to understand with examples. Variables in Python are just the references to the objects in the memory.

What is a strong reference cycle?

A strong reference cycle is when two instances of classes reference each other without the proper safeties ( weak / unowned ) hence preventing the garbage collector from disposing of them once all the variables I created stopped referencing those objects.

Does Python automatically delete unused objects?

When objects are no longer needed, Python automatically reclaims memory from them. However, understanding how GC works can help you write better and faster Python programs.

How does Python handle circular references?

Python ordinarily frees most objects as soon as their reference count reaches zero. (I say "most" because it never frees, for example, small integers or interned strings.) In the case of circular references, this never happens, so the garbage collector periodically walks memory and frees circularly-referenced objects.


2 Answers

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) 
like image 96
Platinum Azure Avatar answered Oct 13 '22 09:10

Platinum Azure


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.

like image 40
Fred Foo Avatar answered Oct 13 '22 09:10

Fred Foo