RuntimePython Error

RecursionError

RecursionError: maximum recursion depth exceeded

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    factorial(5)
RecursionError: maximum recursion depth exceeded

What 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

Broken
def factorial(n):
    return n * factorial(n - 1)

factorial(5)

Fixed code

Fixed
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # 120

About 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

1

Infinite recursion from missing or incorrect base cases

2

Modifying dictionaries or sets during iteration

3

Calling generators or coroutines in unsupported ways

4

Using asyncio event loops incorrectly or attempting to nest them

Related errors