Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python max recursion, question about sys.setrecursionlimit()

Tags:

I have one question about sys.setrecursionlimit()

From the python docs this function:
Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care because a too-high limit can lead to a crash.

Here is my question:

Let's take this useless recursive function:

def rec(N):      if N==0:          return 1      else:          return rec(N-1); 

Now let's set the max recursion to 100:

sys.setrecursionlimit(100) 

If I try rec(99) (100 recursive calls), I get:

RuntimeError: maximum recursion depth exceeded 

To calculate rec(99) I need to set recursion limit to 105.

Why is this so?

like image 703
Ricky Bobby Avatar asked Aug 16 '11 16:08

Ricky Bobby


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.

How do you limit recursion in Python?

The Python interpreter limits the recursion limit so that infinite recursions are avoided. The “sys” module in Python provides a function called setrecursionlimit() to modify the recursion limit in Python. It takes one parameter, the value of the new recursion limit. By default, this value is usually 10^3.

How do I fix maximum recursion depth exceeded in comparison Python?

Conclusion. The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.

What is the maximum recursion limit?

The recursion limit is usually 1000.


1 Answers

It's poorly named. It should say Stack Depth, not Recursion depth. Recursion implies it's the same thread over and over again that it's limiting. In reality, you could have actual code that just has calls 100 deep. I wouldn't recommend it, but you could. They can get away with it because in the practical world, the only times you ever run into this scenario is with recursion. When you crash because of this, seeing the word "Recursion" gives you an immediate clue of what to look for as opposed to "Stack".

(Stack should give any decent programmer the same clue, but let's be honest, your code just crashed and you want a relevant error message, right? 99.99999% of the time this tells you exactly what you messed up (you missed your base case for recursion.))

like image 144
corsiKa Avatar answered Sep 27 '22 20:09

corsiKa