Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Python raises RecursionError before it exceeds the real recursion limit?

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() ?

like image 905
DarkSuniuM Avatar asked Apr 07 '19 14:04

DarkSuniuM


People also ask

How do you fix RecursionError maximum recursion depth exceeded?

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.

Why does Python have a maximum recursion depth?

Python uses a maximum recursion depth of 1000 to ensure no stack overflow errors and infinite recursions are possible.

How do I fix RecursionError maximum recursion depth exceeded while calling a Python object?

Two options you have are: Increase the value of the recursion limit for the Python interpreter. Use iteration instead of recursion.

How do you fix a recursion error in Python?

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.


1 Answers

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.

like image 90
Martijn Pieters Avatar answered Sep 28 '22 11:09

Martijn Pieters