[Tutor] python memory management

Peter Otten __peter__ at web.de
Sat Sep 3 08:26:12 EDT 2016


monikajg at netzero.net wrote:

> 
> By:
> "reference cycles: if one object has a reference to another, and
> that second object also has a reference to the first, that's a cycle."
> 
> Is this what you mean?
> a = 5
> b = a
> a = b

No. int instances are immutable. The assignments above bind both /names/ a 
and b to the same instance of int -- 5. The last statement a = b is 
redundant as a is already bound to 5.

For a reference cycle you need something in an object x to refer to another 
y and vice versa. x and y here are not Python names, but the actual objects.

An example using lists:

>>> a = ["a"]
>>> b = ["b"]

Let's append b to a:
>>> a.append(b)
>>> a[1]
['b']
>>> a[1][1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

We don't have a cycle yet, so Python eventually complains.
Now let's complete the cycle by appending b to a.

>>> b.append(a)
>>> a[1][1]
['a', ['b', [...]]]
>>> a[1][1][1][1][1]
['b', ['a', [...]]]

We can keep accessing x[1] forever, and if Python weren't smart enough to 
detect the cycle instead of producing the [...] it would continue building 
the string representation for the nested lists until all available memory 
was consumed or the stack overflowed.

Another example with a custom class:

>>> class C:
...    def __init__(self, name): self.name = name
...    def __repr__(self): return self.name
... 
>>> a = C("a")
>>> b = C("b")
>>> a
a
>>> b
b
>>> a.b = b
>>> b.a = a
>>> a.b.a.b.a.b.a.b.a.b.a
a

A cycle may of course consist of more than two objects:

>>> a = C("a")
>>> b = C("b")
>>> c = C("c")
>>> a.b = b
>>> b.c = c
>>> c.a = a
>>> c.a.b.c
c
>>> c.a.b.c.a.b.c.a.b.c
c

The minimal cycle consists of an object referencing itself:

>>> a = C("a")
>>> a.a = a
>>> a.a.a.a.a.a.a
a




More information about the Tutor mailing list