RecursionError
PythonERRORCriticalRuntime ErrorHIGH confidence

Maximum recursion depth exceeded

What this means

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.

Why it happens
  1. 1A recursive function that does not have a valid base case to stop the recursion.
  2. 2A base case that is never met due to a logical error.
  3. 3The problem being solved genuinely requires a recursion depth greater than Python's limit, though this is rare.
How to reproduce

This error is triggered by a function that calls itself without any condition to stop it from doing so.

trigger — this will error
trigger — this will error
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.

Add a base case to the recursive function
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.

Rewrite the function iteratively
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.

Code examples
Triggerpython
def infinite():
    return infinite()  # RecursionError: maximum recursion depth exceeded
infinite()
Handle with try/exceptpython
try:
    result = deep_recursive(n)
except RecursionError:
    print("Stack too deep, use iterative approach")
Avoid with iterative approachpython
def factorial(n):
    acc = 1
    while n > 1:
        acc *= n
        n -= 1
    return acc
What not to do

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.

Version notes

Sources
Official documentation ↗

cpython/Python/ceval.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors