Last updated: Apr 8, 2024
Reading timeยท3 min
The Python "RecursionError: maximum recursion depth exceeded" occurs when a function is being called so many times that the invocations exceed the recursion limit.
To solve the error, specify a base case that has to be met to exit the recursion or set a higher recursion limit.
Here is an example of how the error occurs.
def example(): example() # โ๏ธ RecursionError: maximum recursion depth exceeded example()
We call the function, which then calls itself until the recursion limit is exceeded.
You can get the current value of the recursion limit by using the
sys.getrecursionlimit()
method.
import sys # ๐๏ธ 1000 print(sys.getrecursionlimit()) # ๐๏ธ Set recursion limit to 2000 sys.setrecursionlimit(2000) # ๐๏ธ 2000 print(sys.getrecursionlimit())
The getrecursionlimit() method returns the maximum depth of the Python interpreter stack.
You can use the setrecursionlimit() method if you need to update this value.
To solve the error from the example, we have to specify a condition at which the function stops calling itself.
counter = 0 def example(num): global counter if num < 0: return # ๐๏ธ This stops the function from endlessly calling itself counter += 1 example(num - 1) example(3) print(counter) # ๐๏ธ 4
This time we check if the function was invoked with a number that is less than
0
on every invocation.
0
, we simply return from the function so we don't exceed the maximum depth of the Python interpreter stack.If the passed-in value is not less than zero, we call the function with the
passed in value minus 1
, which keeps us moving toward the case where the if
check is satisfied.
You might also get this error if you have an infinite loop that calls a function somewhere.
def do_math(a, b): return a + b while True: result = do_math(10, 10) print(result)
while
loop keeps calling the function and since we don't have a condition that would exit the loop, we eventually exceed the interpreter stack.This works in a very similar way to a function calling itself without a base condition.
Here's an example of how to specify a condition that has to be met to exit the loop.
def do_math(a, b): return a + b total = 0 i = 10 while i > 0: total += do_math(5, 5) i = i - 1 print(total) # ๐๏ธ 100
If the i
variable is equal to or less than 0
, the condition in the while
loop is not satisfied, so we exit the loop.
If you can't track exactly where your error occurs, look at the error message.
The screenshot above shows that the error occurred on line 84
in the
example()
function.
You can also see that the error occurred in the main.py
file.