PythonMastery
reference 3 min read · lesson 23 of 45 in Errors

RecursionError: maximum recursion depth exceeded

1 · The lesson

read

What this error means

Every function call adds a frame to Python's call stack. The interpreter caps how many frames a single thread may stack (default 1000, exposed by sys.getrecursionlimit()). When a recursive function exceeds the cap — almost always because the base case is missing or wrong — Python raises RecursionError to protect you from a C-level stack overflow that would crash the process.

When you see it

text
Traceback (most recent call last):
  File "fib.py", line 7, in <module>
    print(fib(30))
  File "fib.py", line 4, in fib
    return fib(n - 1) + fib(n - 2)
  File "fib.py", line 4, in fib
    return fib(n - 1) + fib(n - 2)
  File "fib.py", line 4, in fib
    return fib(n - 1) + fib(n - 2)
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

The classic Fibonacci with a missing base case:

python
def fib(n):
    # forgot: if n < 2: return n
    return fib(n - 1) + fib(n - 2)

Why it happens

Three usual causes, in order of frequency: (1) the base case is missing entirely, (2) the base case exists but the recursive call never approaches it (e.g. fact(n) calling fact(n) instead of fact(n - 1)), (3) the problem genuinely needs more than ~1000 levels of recursion, such as walking a very deep tree.

How to fix it

Option 1 — add or fix the base case. This fixes 95% of real bugs.

python
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

Option 2 — convert to iteration. Faster, no stack risk, and often clearer.

python
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Option 3 — raise the limit (the brittle option). Use only when you genuinely need depth, e.g. parsing deeply nested JSON.

python
import sys
sys.setrecursionlimit(10_000)

This costs memory and pushes the problem onto the C stack — Python may still crash hard. Prefer iteration or an explicit list-based stack.

Option 4 — memoise. Doesn't fix infinite recursion but stops redundant deep calls in algorithms like Fibonacci.

python
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

When you'd actually see this in real code

  • A directory walker that follows symlinks without cycle detection.
  • A JSON or HTML tree traversal where the data is deeper than expected.
  • A __repr__ or __eq__ that delegates back to itself.
  • MemoryError — recursion limit raised so high you ran out of RAM.
  • RuntimeError — what RecursionError was called before Python 3.5; you may still see it in old code.

See Also