Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting recursive nested list in Python

Tags:

python

Say I create a recursive nested list in Python like this:

>>> a = [1,2]
>>> a += [a]

Some properties:

  • len(a) is 3
  • a[2] is a is True

What happens when you print out a? This appears:

>>> a
[1, 2, [...]]

Similarly:

>>> a[2]
[1, 2, [...]]

Why? How does Python "know" the recursion within the list? How is the recursion detected?

like image 289
hongsy Avatar asked Dec 24 '22 07:12

hongsy


1 Answers

When Python constructs the repr of a builtin object such as a list it uses two internal functions: Py_ReprEnter(PyObject *), and Py_ReprLeave(PyObject *).

The first of these functions checks we are already handling the repr for the specified object (i.e. looks to see whether it is currently remembering that object). If not it remembers the object and returns 0. In that case the repr code prints the object then calls Py_ReprLeave which removes the object from the set that are currently being tracked.

If Py_ReprEnter is already tracking the object it returns non 0 and in that case the list repr code prints [...].

like image 193
Duncan Avatar answered Dec 28 '22 16:12

Duncan