Maximum recursion depth exceeded
A subclass of `RuntimeError`, this is raised when the interpreter detects that the maximum recursion depth has been exceeded. This is a guard against a stack overflow from infinite recursion.
- 1A recursive function that does not have a valid base case to stop the recursion.
- 2A base case that is never met due to a logical error.
- 3The problem being solved genuinely requires a recursion depth greater than Python's limit, though this is rare.
This error is triggered by a function that calls itself without any condition to stop it from doing so.
def countdown(n):
print(n)
countdown(n - 1) # No base case to stop recursion
countdown(10)
expected output
Traceback (most recent call last): File "<stdin>", line 5, in <module> ... File "<stdin>", line 3, in countdown RecursionError: maximum recursion depth exceeded in comparison
Fix 1
Add a base case to the recursive function
WHEN Every recursive function must have a condition to terminate.
def countdown(n):
if n < 0: # Base case
return
print(n)
countdown(n - 1)
countdown(10)
Why this works
The `if n < 0:` condition acts as a 'base case'. When `n` becomes negative, the function returns without making another recursive call, thus ending the chain.
Fix 2
Rewrite the function iteratively
WHEN The problem can be solved more simply or efficiently with a loop.
def countdown_iterative(n):
while n >= 0:
print(n)
n -= 1
countdown_iterative(10)
Why this works
A `while` loop can often achieve the same result as recursion without consuming stack space, making it safer for tasks that require many iterations.
def infinite():
return infinite() # RecursionError: maximum recursion depth exceeded
infinite()try:
result = deep_recursive(n)
except RecursionError:
print("Stack too deep, use iterative approach")def factorial(n):
acc = 1
while n > 1:
acc *= n
n -= 1
return acc✕ Dramatically increasing the recursion limit with `sys.setrecursionlimit()`
This usually just papers over a bug (infinite recursion) and can cause a real stack overflow, which will crash the Python interpreter itself.
cpython/Python/ceval.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev