PythonMastery
reference 3 min read · lesson 23 of 60 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 limits how many frames a single thread can have on the stack (the default is 1000, and sys.getrecursionlimit() returns the current value). When a recursive function goes past this limit, 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 really 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 most real bugs.

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

Option 2: convert to iteration. A loop is faster, cannot overflow the stack, and is 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 fragile option). Use this only when you really need the depth, for example when parsing deeply nested JSON.

python
import sys
sys.setrecursionlimit(10_000)

This costs memory and moves the problem to the C stack, so Python may still crash completely. Prefer iteration or an explicit list-based stack.

Option 4: memoise. This doesn't fix infinite recursion, but it stops repeated calls with the same argument 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 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: the recursion limit was raised so high that you ran out of RAM.
  • RuntimeError: what RecursionError was called before Python 3.5. You may still see it in old code.

See Also

Found this useful? Share it with a friend who’s learning Python.