[Tutor] python memory management

monikajg at netzero.net monikajg at netzero.net
Sat Sep 3 17:16:52 EDT 2016


So what does [...] mean?

---------- Original Message ----------
From: Peter Otten <__peter__ at web.de>
To: tutor at python.org
Subject: Re: [Tutor] python memory management
Date: Sat, 03 Sep 2016 14:26:12 +0200

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


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

____________________________________________________________
howlifeworks.com (Sponsored by Content.Ad)
Why Women Are Flocking to This Incredible New Shopping Site
http://thirdpartyoffers.netzero.net/TGL3241/57cb3e00e29ee3e000c94st01duc


More information about the Tutor mailing list