So I was trying to play with sys.getrecursionlimit()
and sys.setrecursionlimit()
methods.
By default recursion limit was 3000
.
I tried to check it using this code:
def recursive(n):
print(n)
recursive(n+1)
recursive(0)
It does print the numbers to 2979
, it delays for a second, prints 2980
and then raises the RecursionError
RecursionError: maximum recursion depth exceeded while calling a Python object
I know that error should be raised when it exceeds recursion limit that sys.getrecursionlimit()
returns, but it doesn't
Seems like it always doing it 20times before the recursion limit
I also tried this:
sys.setrecursionlimit(100)
def recursive(n):
print(n)
recursive(n+1)
recursive(0)
It still does the same thing, prints all the numbers to 79
, delays for a second, prints 80
and then raises the very same error
Why it does raise the error before it exceeds the real recursion limit that we set or get by sys.getrecursionlimit()
?
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.
Python uses a maximum recursion depth of 1000 to ensure no stack overflow errors and infinite recursions are possible.
Two options you have are: Increase the value of the recursion limit for the Python interpreter. Use iteration instead of recursion.
Try increasing the recursion limit ( sys. setrecursionlimit ) or re-writing your code without recursion. Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
Your recursive()
function is not the only component that counts towards the limit. Some Python internals also increase the counter, because Python code can cause them to be called multiple times too. The print()
function is one of them.
Bottom line is that the recursion limit doesn't only apply to the Python functions you wrote. It applies to the whole call stack.
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