DEV Community

Yunus Emre Güzel
Yunus Emre Güzel

Posted on Originally published at blog.emreguzel.ca

RecursionError: Maximum Recursion Depth Exceeded (Fix)

Your script runs for a moment. Then Python dumps a huge traceback that ends like this:

RecursionError: maximum recursion depth exceeded
Enter fullscreen mode Exit fullscreen mode

A function kept calling itself until Python pulled the plug. Below are the six reasons that happens in real programs, the message each one gives, and how to fix it. I ran every example on Python 3.11, 3.12 and 3.14. All three raise RecursionError. The words after “exceeded” change a little between versions, and I flag it where it matters.

What the Error Means

A recursive function calls itself. Each call waits for the next one to finish, so Python has to remember every unfinished call. That memory is called the “call stack”, and it's limited. By default Python allows 1000 nested calls. You can check the limit with sys.getrecursionlimit(). Go past it and Python raises RecursionError rather than letting the program crash.

Two very different problems hide behind this one message. Usually the recursion would never end, and that's a logic bug (causes 1 to 5). Sometimes the recursion is fine but needs more than 1000 levels (cause 6). The fixes don't match, so work out which case you have first.

How to Find the Cause Fast

The traceback is long, but only two parts matter. Look at the last lines to see which function keeps getting called. The same one or two lines repeat above them. Python squeezes the repeats into a line like [Previous line repeated 996 more times]. Now ask yourself: with the input I gave it, would this function ever stop? Put a print of the argument at the top and run it with a small input:

def countdown(n):
    print("countdown", n)      # watch the argument: does it move toward the end?
    ...
Enter fullscreen mode Exit fullscreen mode

Does the argument move toward the stopping point? Then it's cause 6. If it never gets there, or the function ignores its argument, you have one of causes 1 to 5.

The Six Causes

1. There Is No Base Case

def countdown(n):
    print(n)
    countdown(n - 1)                   # never stops: there is no base case


countdown(3)                           # RecursionError: maximum recursion depth exceeded
Enter fullscreen mode Exit fullscreen mode

A recursive function needs a base case. That's a condition where it returns without calling itself again. Leave it out and the calls pile up forever. Add the check that says when to stop:

def countdown(n):
    if n < 0:                          # base case: when to stop
        return
    print(n)
    countdown(n - 1)


countdown(3)
Enter fullscreen mode Exit fullscreen mode

2. The Base Case Is Never Reached

def factorial(n):
    if n == 0:                         # the base case is only reached from 0
        return 1
    return n * factorial(n - 1)


print(factorial(-3))                   # -3, -4, -5 ... never hits 0: RecursionError
Enter fullscreen mode Exit fullscreen mode

This function has a base case. But it only fires when n is exactly 0. Start at -3 and the value walks to -4, -5 and keeps going. Common culprits are an == that should be <=, a step that goes the wrong way, or an input nobody planned for. Compare more safely, and turn away bad input right at the start:

def factorial(n):
    if n < 0:
        raise ValueError("factorial needs n >= 0")
    if n <= 1:                         # <= is safer than ==
        return 1
    return n * factorial(n - 1)


print(factorial(5))
Enter fullscreen mode Exit fullscreen mode

3. A Property That Returns Itself

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

    def __init__(self, name):
        self._name = name


print(User("Ana").name)                # RecursionError
Enter fullscreen mode Exit fullscreen mode

This one is confusing because you can't see any recursion. But look inside the name property. self.name asks for the property again, which runs the same code again, and round it goes. A setter that assigns to self.name does the same thing. Keep the real data under another name, usually with a leading underscore:

class User:
    def __init__(self, name):
        self._name = name              # store the data under a different name

    @property
    def name(self):
        return self._name


print(User("Ana").name)
Enter fullscreen mode Exit fullscreen mode

4. repr or str That Prints a Cycle

class Node:
    def __init__(self, label):
        self.label = label
        self.other = None

    def __repr__(self):
        return f"Node({self.label}, {self.other!r})"


a, b = Node("a"), Node("b")
a.other, b.other = b, a                # a points to b, b points back to a
print(repr(a))                         # RecursionError while getting the repr of an object
Enter fullscreen mode Exit fullscreen mode

Object a points to b, and b points back to a. Printing a means printing b, which means printing a again. Python's built-in lists and dictionaries cope with this (a list that contains itself prints as [...]). Your own __repr__ won't. So print a label for the linked object, not the whole thing. On Python 3.11 and 3.12 the message ends with while getting the repr of an object:

class Node:
    def __init__(self, label):
        self.label = label
        self.other = None

    def __repr__(self):
        other = self.other.label if self.other else None   # print the label, not the whole object
        return f"Node({self.label}, other={other})"


a, b = Node("a"), Node("b")
a.other, b.other = b, a
print(repr(a))
Enter fullscreen mode Exit fullscreen mode

5. Two Functions That Call Each Other

def is_even(n):
    return True if n == 0 else is_odd(n - 1)


def is_odd(n):
    return False if n == 0 else is_even(n - 1)


print(is_even(-1))                     # -1 never reaches 0: the two functions call each other forever
Enter fullscreen mode Exit fullscreen mode

is_even calls is_odd, and is_odd calls is_even. Give it a positive number and it works. A negative number never reaches 0. This kind of mutual recursion is sneaky, because each function looks fine on its own. The best fix here is to get rid of the recursion:

def is_even(n):
    return n % 2 == 0                  # no recursion needed


print(is_even(-1), is_even(10))
Enter fullscreen mode Exit fullscreen mode

6. The Recursion Is Correct but Too Deep

def total(n):
    if n == 0:
        return 0
    return n + total(n - 1)            # correct, but needs 5000 nested calls


print(total(5000))                     # RecursionError: Python stops at about 1000 calls
Enter fullscreen mode Exit fullscreen mode

The logic is fine. It adds the numbers from 1 to 5000. But that takes 5000 nested calls, and Python stops at about 1000. A long list, a long string or a big number can trigger this in any recursive solution. Use a loop, since a loop doesn't touch the call stack. Or use a built-in like sum():

def total(n):
    result = 0
    for i in range(1, n + 1):          # a loop uses no call stack
        result += i
    return result


print(total(5000))
print(sum(range(1, 5001)))             # or use the built-in
Enter fullscreen mode Exit fullscreen mode

Should You Raise the Limit?

You can. sys.setrecursionlimit(10000) makes the 5000-deep example work, and I ran that on Python 3.11 and 3.14. Still, keep it as a last resort. An infinite recursion stays infinite. The error just shows up later. The limit is there because every call costs real memory. Set it too high and Python can crash outright instead of giving you a clean error. Only raise it when you know the depth is finite and moderate. Deeper than that? Rewrite the function as a loop.

Two techniques help if you'd like to keep the recursive style. Memoisation: functools.lru_cache remembers the results of earlier calls. That turns a slow recursive Fibonacci into a fast one (I ran fib(90) with it and it finished instantly). An explicit stack: keep your own list of work still to do, and handle it in a while loop. That's how people usually write deep tree walks when the depth is unknown.

Quick Reference

Symptom Fix
Function never returns without calling itself Add a base case
Base case exists but is skipped Use <=, check the step direction, validate the input
Error inside a property or __init__ Store data in self._name, not self.name
Error while printing an object Print a label for linked objects in __repr__
Two functions in the traceback, alternating Fix both base cases, or remove the recursion
Logic is right but input is large Use a loop, a built-in, or an explicit stack

The Rule, Stated Once

RecursionError means a function called itself more than about 1000 times in a row. Ask whether it would ever stop. If not, add or repair the base case. If it would, swap the recursion for a loop. Raising the limit usually hides the problem instead of solving it.

Other Python errors with a clear cause are FileNotFoundError, KeyError in Python, TypeError: NoneType Is Not Subscriptable and UnboundLocalError. If Python is new to you, start with Python for Beginners.

Download the code: the broken and fixed versions of all six causes are on GitHub in Python-projects/Troubleshooting/recursionerror. Run any file with python bug.py from inside its folder.

Top comments (0)