RecursionError
RecursionError: maximum recursion depth exceeded
Traceback
Traceback (most recent call last):
File "main.py", line 4, in <module>
factorial(5)
RecursionError: maximum recursion depth exceededWhat causes this error
A function calls itself (directly or indirectly) more times than the recursion limit allows. This usually means a missing or incorrect base case in a recursive function, or an algorithm that requires more depth than Python's limit.
How to fix it
Ensure your recursive function has a correct base case that terminates recursion. Convert deep recursion to iterative algorithms using a stack. Use `functools.lru_cache` for memoization. Only increase `sys.setrecursionlimit()` as a last resort.
Code that causes this error
def factorial(n):
return n * factorial(n - 1)
factorial(5)Fixed code
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120About RecursionError
A RecursionError is raised when the maximum recursion depth is exceeded. Python has a default recursion limit (usually 1000, checkable via `sys.getrecursionlimit()`) that prevents infinite recursion from consuming all available stack memory and crashing the interpreter. This error typically indicates either a genuinely infinite recursion (a function that calls itself without a proper base case), or an algorithm that requires deeper recursion than the default limit allows.
While you can increase the limit with `sys.setrecursionlimit()`, this is rarely the right fix — it just delays the crash if the recursion is truly infinite, and deep recursion in Python is slow due to function call overhead. The proper solutions are to fix the base case for infinite recursion, convert recursive algorithms to iterative ones using explicit stacks or loops, or use memoization (via `functools.lru_cache`) to avoid redundant recursive calls.
Common scenarios
Infinite recursion from missing or incorrect base cases
Modifying dictionaries or sets during iteration
Calling generators or coroutines in unsupported ways
Using asyncio event loops incorrectly or attempting to nest them