Coding

RecursionError: Maximum Recursion Depth Exceeded in Python (Fix)

RecursionError: maximum recursion depth exceeded means a function called itself (directly or through other functions) deeper than Python's recursion limit allows. First check whether the recursion can ever stop, meaning it has a base case and every call moves towards it; if it is correct but too deep, rewrite it as a loop or raise the limit with sys.setrecursionlimit().

The Python documentation says RecursionError is derived from RuntimeError and is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit()) is exceeded. Before Python 3.5 the same situation raised a plain RuntimeError.

What the error looks like

This function has no base case, so it can only end by hitting the limit:

def countdown(n):
    return countdown(n - 1)

countdown(10)

Example output (Python 3.12, path shortened):

Traceback (most recent call last):
  File "C:\work\demo.py", line 4, in <module>
    countdown(10)
  File "C:\work\demo.py", line 2, in countdown
    return countdown(n - 1)
           ^^^^^^^^^^^^^^^^
  File "C:\work\demo.py", line 2, in countdown
    return countdown(n - 1)
           ^^^^^^^^^^^^^^^^
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

Python collapses identical repeated frames into [Previous line repeated N more times]. The repeated line is your clue: it is the call that keeps recursing. If the traceback format is unfamiliar, how to read a stack trace walks through it.

Step 1: find out whether the recursion is infinite

Print the current limit, then run the function on a tiny input:

import sys
print(sys.getrecursionlimit())

If the function fails even for an input of 1 or 2, it is almost certainly an infinite recursion, not a depth problem. If it works for 10 and fails for 10,000, depth is the issue. That one test decides which of the two fix paths below you need.

Cause 1: a missing or unreachable base case

Every recursive function needs a condition that returns without calling itself. Compare:

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

factorial(5)    # 120
factorial(-1)   # RecursionError: -1, -2, -3 ... never equals 0

Changing the base case to n <= 1 makes the negative input return 1, which may still be wrong for your problem. Often the better fix is to validate the input and raise a ValueError for negative numbers, so the mistake is reported where it was made.

Cause 2: the recursive step does not shrink the problem

The call must pass a smaller or simpler input. These are the usual slips:

  • Calling f(n) where you meant f(n - 1).
  • Passing the whole list again where you meant items[1:].
  • Computing a midpoint in binary search and then recursing on a range that still includes the same elements, so the range never gets smaller.
  • Walking a graph or a data structure with cycles (a node that points back to an ancestor) without remembering which nodes you have already visited.

For the graph case, keep a visited set and return early when a node is already in it. Otherwise a cycle makes the recursion endless no matter how large the limit is.

Cause 3: accidental recursion

Some recursion is not obvious from reading the function. The classic case is a property that reads itself:

class User:
    @property
    def name(self):
        return self.name      # calls the property again, forever

The fix is to store the value under a different attribute, such as self._name. The same pattern shows up in __setattr__ that assigns self.x = value (which calls __setattr__ again), in __repr__ methods that print an object that contains itself, and in two functions that call each other with no exit condition. The repeated lines in the traceback name every function in the loop.

Cause 4: correct recursion on deep input

If the base case is right and the step shrinks the input, but the input is simply deep, the code is fine and the default limit is too low for it. Typical examples are one call per item of a long list, a linked list with thousands of nodes, or a deeply nested structure. You have three options, in the order worth trying.

Option A: rewrite it as a loop

This is the most reliable fix, because a loop has no depth limit. A recursive sum over a linked list:

def total(node):
    if node is None:
        return 0
    return node.value + total(node.next)

becomes:

def total(node):
    result = 0
    while node is not None:
        result += node.value
        node = node.next
    return result

For tree or graph traversal, where a simple loop does not fit, replace the call stack with your own list used as a stack:

def count_nodes(root):
    stack = [root]
    count = 0
    while stack:
        node = stack.pop()
        count += 1
        stack.extend(node.children)
    return count

This visits every node without ever nesting a function call, so the depth is limited by memory, not by the interpreter. CPython does not turn a recursive call in tail position into a loop, so writing a function in tail-recursive style does not avoid the limit.

Option B: raise the limit, carefully

import sys
sys.setrecursionlimit(5000)

The documentation says the limit exists to stop infinite recursion from overflowing the C stack and crashing Python. It also says the highest possible limit is platform-dependent and that setting it too high can lead to a crash. Raise it moderately, to a value just above the depth you actually need, and test on the platform you deploy to. Since Python 3.5.1, setting a limit that is too low for the current depth itself raises RecursionError.

Raising the limit does nothing for an infinite recursion. It only makes the program run longer before failing, and with a very large value it can end in a hard crash of the interpreter instead of a catchable exception.

Option C: memoize, if the real problem is repeated work

Naive recursive functions such as Fibonacci recompute the same values many times. functools.cache (added in Python 3.9) remembers results:

from functools import cache

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

The documentation describes cache as the same as lru_cache(maxsize=None), and notes the function's arguments must be hashable because a dictionary stores the results. Memoization speeds up the function but does not reduce its depth: a first call to fib(5000) still nests 5,000 calls deep. Combine it with a loop, or fill the cache from the bottom up with a loop, if depth is the problem.

Catching RecursionError

You can catch it like any exception:

try:
    result = walk(document)
except RecursionError as error:
    raise ValueError("document is nested too deeply") from error

This is reasonable at an input boundary, where the cause is untrusted data nested absurdly deep, and the right response is a clear error. Inside your own logic, a caught RecursionError usually hides a bug.

Quick decision table

SymptomLikely causeFix
Fails even for tiny inputsNo base case, or input never shrinksAdd or correct the base case; check each call moves towards it
Fails only for negative or empty inputBase case unreachable for that inputValidate input, or widen the base case
Traceback names a property or __setattr__Accidental self-referenceStore the value in a separate attribute
Fails on cyclic dataNo visited setTrack visited nodes
Works for 500, fails for 5,000Depth grows with input sizeRewrite as a loop; raise the limit only as a stopgap

If it still fails

Print the argument at the top of the function for the first 20 calls or so. If the values repeat or move away from the base case, the bug is in the step. If they shrink steadily and the failure only comes at the limit, the input is deep and you need a loop. If you raised the limit and the program now exits without a Python traceback at all, the stack overflowed at the C level; lower the limit and use the iterative version instead.

Frequently asked questions

What does RecursionError: maximum recursion depth exceeded mean?
Python raised RecursionError because a chain of function calls got deeper than the interpreter's recursion limit. The Python documentation says the exception is raised when the interpreter detects that the maximum recursion depth, the value returned by sys.getrecursionlimit(), is exceeded. Either the recursion never ends because of a bug, or it is correct but needs more depth than the limit allows.
What is the default recursion limit in Python?
In CPython it is normally 1000. The Python documentation does not publish the number, so print it with sys.getrecursionlimit() on your own install. You can change it with sys.setrecursionlimit(), but the documentation warns that a too-high limit can crash the interpreter.
Is RecursionError an Exception I can catch?
Yes. It is derived from RuntimeError, so except RecursionError works. Catching it is rarely the right fix, because it hides a bug or a design problem. It is reasonable at a boundary, for example to reject absurdly nested user input with a clear error message.
Why does my recursive function work for small inputs and fail for big ones?
The recursion depth grows with the input. A function that calls itself once per item needs one stack frame per item, so a list of 5,000 items needs about 5,000 levels. Small inputs stay under the limit; large ones go over it. Rewriting the function as a loop removes the dependence on input size.

Sources