RecursionError: maximum recursion depth exceeded
A function is calling itself too many times. Python’s default limit is 1000 recursive calls.
Fix 1: Add or fix the base case
# ❌ No base case — infinite recursion
def factorial(n):
return n * factorial(n - 1)
# ✅ Add a base case
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
Fix 2: Check for accidental recursion
# ❌ __str__ calls itself via string formatting
class User:
def __str__(self):
return f"User: {self}" # Calls __str__ again!
# ✅ Reference the attribute, not the object
class User:
def __str__(self):
return f"User: {self.name}"
Fix 3: Convert to iteration
If the recursion is legitimate but deep, rewrite it as a loop:
# ❌ Recursive — fails for large lists
def flatten(lst):
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
# ✅ Iterative with a stack
def flatten(lst):
stack, result = [lst], []
while stack:
current = stack.pop()
if isinstance(current, list):
stack.extend(current)
else:
result.append(current)
return result
Fix 4: Increase the limit (last resort)
import sys
sys.setrecursionlimit(5000)
This is a band-aid. If you need more than 1000 levels, you probably need an iterative approach instead.
Debugging tip
Add a counter to see where the recursion goes wrong:
def my_func(n, depth=0):
print(f"depth={depth}, n={n}")
if depth > 20:
raise Exception("Too deep — check your logic")
return my_func(n - 1, depth + 1)
See also: Python cheat sheet | Maximum call stack exceeded fix (JavaScript equivalent)