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?
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 [...]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With