I was trying to experimentally determine Python's maximum recursion depth with the following code:
def recursive(i):
i = i + 1
try:
recursive(i)
except RuntimeError:
print 'max depth == %d' % i
exit(0)
recursive(0)
But when I ran it, this happened:
[ hive ~ ]$ python recursive.py
max depth == 999
max depth == 998
max depth == 997
max depth == 996
max depth == 995
max depth == 994
Why is my program not exiting right away when it encountered RuntimeError
the first time, but continued to run for 5 more calls to recursive()
?
The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.
The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.
Due to this, the recursion limit of python is usually set to a small value (approx, 10^4). This means that when you provide a large input to the recursive function, you will get an error. This is done to avoid a stack overflow. The Python interpreter limits the recursion limit so that infinite recursions are avoided.
You are using the exit()
function the Python site
module sets for use in the interactive interpreter.
This is Python code you are calling, not C code. This triggers the recursion depth exception handler a few more times until you are far enough away from the stack limit.
When you are right up against the limit, trying to call exit()
fails because you hit the stack limit. So a RuntimeError
is raised, falling back a call to 998
. Here you try to call exit()
again, which tries to do some more work raising the RuntimeError
again, falling back another level, etc. until there is enough stack space left to finally call raise SystemExit()
in the python function.
Use sys.exit()
instead to avoid adding more strain to the stack.
Or, for future reference, use the sys.getrecursionlimit()
function to just ask Python directly what the limit is.
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