Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

Python RecursionError

Reference for Python RecursionError: why maximum recursion depth is exceeded, base cases, sys.setrecursionlimit(), and converting recursion to loops.

RecursionError is raised when the interpreter's call stack gets deeper than the allowed limit. The message is maximum recursion depth exceeded, sometimes followed by while calling a Python object or in comparison.

Almost always the cause is a recursive function that never reaches its base case. The limit exists so that such a bug fails fast with a traceback instead of crashing the whole process. RecursionError is a subclass of RuntimeError.

Python
def forever(n):
    return forever(n + 1)

forever(0)   # RecursionError: maximum recursion depth exceeded

Try it

Python A missing base case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Deep but valid recursion: three ways out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
import sys

sys.getrecursionlimit()        # current limit
sys.setrecursionlimit(5000)    # change it (use with care)

try:
    solve(data)
except RecursionError:
    ...
Name Description
sys.getrecursionlimit() Returns the maximum depth of the Python call stack. The default is about 1000 in most builds.
sys.setrecursionlimit(n) Sets the limit. Raises ValueError if n is too low for the current depth.

Raises when: the number of nested Python calls would exceed the limit. Some builtins (comparisons, repr() of self-referencing structures, deeply nested JSON) also raise it.

Usage notes

  • Check the base case first. Every recursive function needs a case that returns without recursing, and each call must move closer to it. The n - 2 example skips past 0 when n is odd.
  • Raising the limit is a last resort. A very high value can overflow the real C stack and crash the interpreter with no Python traceback. If you need depth in the thousands, switch to a loop or an explicit stack.
  • Convert to iteration with a while loop and a list used as a stack (depth-first search) or a deque (breadth-first search). Tail calls are not optimized in Python, so a tail-recursive style does not help.
  • Memoize overlapping calls with functools.cache or lru_cache when the same subproblems repeat; this fixes speed, but deep recursion still uses stack.
  • The limit counts frames, not time. A shallow but slow function never raises this error.
  • Where recursion is natural (trees, nested dicts, parsing) the data is usually shallow enough. Be careful with user-supplied data that may be nested arbitrarily deep.
  • Catching it is rarely the right fix; the traceback tells you which function recursed. In production, log the problem and return an error for the request.
  • Different interpreters differ: Python 3.12 and later separate the Python limit from the C-level limit, and other environments such as WebAssembly builds have smaller C stacks.