Recursive structures

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Dec 20 15:28:12 EST 2004


Leif K-Brooks:
>http://python.org/doc/current/lib/module-pprint.html#l2h-749

Thank you very much, I see that the function is already there, even
with the same name :-)

I've seen that it doesn't work for all my tests, like this one with n =
3000:

from pprint import isrecursive
from time import clock
n = 950
print "n =", n
l = []
for i in xrange(n): l = [n-i, l]
if n < 30: print l
t = clock()
assert not isrecursive(l)
print round(clock()-t, 3), "s"

In the function _safe_repr of the pprint.py module there is a recursive
call:
orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)

Probably this _safe_repr function can be modified (with a lot of work?)
to be iterative (using a list as a stack) to avoid such stack overflows
(the list too can overflow, but its capacity is enough for most
purposes). Python doesn't have C-like unsafe buffer overrun, so using a
list as stack probably improves security a little, and probably makes
_safe_repr faster.

See you,
Bearophile




More information about the Python-list mailing list