Recursive lists

D

Duncan Booth

Can someone tell me why python doesn't crash when I do the following:
a=[]
a.append(a)
print a [[...]]
print a[0][0][0][0][0][0][0]
[[...]]

How does python handle this internally? Will it crash or use up lot's
of memory in similar but more complicated cases?

No, it remembers internally which objects it has seen when converting
them with str or repr. The C api includes functions Py_ReprEnter() and
Py_ReprLeave() which the builtin objects call when they enter/leave
repr. If Py_ReprEnter() returns 0 the object will return its
representation, on subsequent calls Py_ReprEnter() returns 1 and the
object knows it is being recursed.

If you have your own recursive data structures then you may have to take
your own precautions against recursion. The simplest way to do this is
to make sure that the recursion always goes through a builtin object
such as a list or dictionary.
.... def __repr__(self):
.... return "<C %r>" % self.inner
.... inner = None
.... File "<stdin>", line 3, in __repr__
File "<stdin>", line 3, in __repr__
File "<stdin>", line 3, in __repr__
... and so on ...
File "<stdin>", line 3, in __repr__
File "<stdin>", line 3, in __repr__
File said:
<C [<C [...]>]>

N.B. Don't use a tuple here as tuples don't check for recursion. That's
because tuples cannot be recursive except by containing another
recursive data structure such as a list, dict, or user-defined object.
 
S

Stargaming

Can someone tell me why python doesn't crash when I do the following:
a=[]
a.append(a)
print a [[...]]
print a[0][0][0][0][0][0][0]
[[...]]

How does python handle this internally? Will it crash or use up lot's of
memory in similar but more complicated cases?

It should be like you pointing your finger at yourself and yelling I
guess. Just a reference, no new object.
 
M

mizrandir

So if I understood correctly the recursive structure isn't a problem
for python because "a" contains a reference to "a", not "a" itself. On
the other hand, print works ok because it has a special trap to detect
recursive structures. I think I understand it now.

Thnks for your replies, miz.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top