Walking deeply nested lists

Peter Otten __peter__ at web.de
Sat Aug 28 08:41:45 EDT 2010


donn wrote:

> On 28/08/2010 12:03, Peter Otten wrote:
>> But be warned that if you set the limit too high instead of giving you a
>> RuntimeError your program will segfault.
> Silly question: is there any way to tell the future in this case? I
> mean, ask for X recursion limit, and catch an error (or something) if
> that won't fly.

I don't think it's a silly question, and I don't think there is an exact 
answer,  even for a given platform. You'll want to stay well below the 
number calculated by the following script:

import os
import subprocess

SCRIPT = "tmp_check.py"

def ok(n):
    return subprocess.call(["python", SCRIPT, str(n)]) == 0

if __name__ == "__main__":
    if not os.path.exists(SCRIPT):
        with open(SCRIPT, "w") as out:
            out.write("""\
import sys

def f():
    return f()

if __name__ == "__main__":
    n = int(sys.argv[1])
    sys.setrecursionlimit(n)
    try: 
        f()
    except RuntimeError:
        pass
""")

    low = 1000
    while True:
        new_low = 2*low
        if not ok(new_low):
            high = new_low
            break
        low = new_low

    while high - low > 1:
        mid = (low + high) // 2
        if ok(mid):
            low = mid
        else:
            high = mid
    print "max recursion limit", low, high

BTW, I didn't expect it but I get different results on different runs.

Peter



More information about the Python-list mailing list