Aguy Aguy - 9 months ago 69
Python Question

Max recursion is not exactly what sys.getrecursionlimit() claims. How come?

I've made a small function that will actually measure the max recursion limit:

def f(x):
r = x
r = f(x+1)
except Exception as e:
return r

To know what to expect I've checked:

In [28]: import sys

In [29]: sys.getrecursionlimit()
Out[29]: 1000


In [30]: f(0)
maximum recursion depth exceeded
Out[30]: 970

The number is not fixed, always around ~970, and slightly changes between different instances of python (e.g. from within spyder to system cmd prompt).

Please note that I'm using ipython on python3.

What's going on? Why is the actual limit I'm getting lower than the

Answer Source

The recursion limit is not the limit on recursion but the maximum depth of the python interpreter stack.There is something on the stack before your function gets executed. Spyder executes some python stuff before it calls your script, as do other interpreters like ipython.

You can inspect the stack via methods in the inspect module.

In CPython for me:


In Ipython for me:


As knbk pointed out in the comments as soon as you hit the stack limit a RecursionError is thrown and the interpreter raises the stack limit a bit to give you a possibility to handle the error gracefully. If you also exhaust that limit python will crash.