RecursionError: What It Means and How to Fix It
Error reference
RecursionError
Language
Severity
CriticalWhen it happens
A RecursionError is raised in Python when a recursive function exceeds the maximum call stack depth, which defaults to 1000 frames.
Potential fixes
Add or fix the base case so every recursive call moves closer to termination. For large inputs, convert the algorithm to an iterative loop. If deep recursion is genuinely required, you can temporarily increase the limit with sys.setrecursionlimit(), but this is a last resort.
Related errors
Deep dive
A RecursionError is raised in Python when a recursive function exceeds the maximum call stack depth, which defaults to 1000 frames. Python tracks each function call on the stack, and when that limit is hit the interpreter stops execution to prevent a stack overflow.
Why it happens
- •A recursive function is missing its base case, causing infinite recursion.
- •The base case exists but the input never reaches it due to a logic error.
- •Legitimate deep recursion on large inputs that genuinely exceeds the default limit.
- •Mutually recursive functions that call each other in a cycle without terminating.
Potential fixes
Add or fix the base case so every recursive call moves closer to termination. For large inputs, convert the algorithm to an iterative loop. If deep recursion is genuinely required, you can temporarily increase the limit with sys.setrecursionlimit(), but this is a last resort.
Examples
Code that triggers the error
def factorial(n):
return n * factorial(n - 1) # missing base case
print(factorial(5))Error output
Traceback (most recent call last):
File "app.py", line 4, in <module>
print(factorial(5))
File "app.py", line 2, in factorial
return n * factorial(n - 1)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceededFixed code
def factorial(n):
if n <= 1: # base case stops the recursion
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120Practice in English
How would you explain a RecursionError to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free