getrecursiondepth
Andrew Dalke
adalke at mindspring.com
Sat Sep 25 20:09:02 EDT 2004
Manlio Perillo wrote:
>>>>foo()
>
> n = 0 and recursion depth = 1
> n = 1 and recursion depth = 2
> n = 2 and recursion depth = 3
> n = 3 and recursion depth = 4
Why is it needed?
Unlike getrecursionlimit it is something that can be
calculated pretty easily.
>>> def getdepth():
... f = sys._getframe()
... i = -1
... while 1:
... try:
... f = f.f_back
... except AttributeError:
... return i
... i = i + 1
...
>>> def test(n):
... if n==0: return getdepth()
... return test(n-1)
...
>>> test(10)
12
>>> test(30)
32
>>> test(sys.getrecursionlimit()-3)
999
>>>
Anything which depends on the exact number is going
to have problems because that depends on the environment.
For example, in idle getdepth() from its shell
returns 4 instead of the 2 found in the command-line
shell.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list