Skip to content
FR
  1. LuzineDebug
  2. Python
  3. RecursionError: maximum recursion depth exceeded
Python Intermediate ≈ 15 min to fix

Fix "RecursionError: maximum recursion depth exceeded" in Python

Error message
RecursionError: maximum recursion depth exceeded
  • RecursionError: maximum recursion depth exceeded while calling a Python object
  • RecursionError: maximum recursion depth exceeded in comparison
  • RecursionError: maximum recursion depth exceeded while getting the str of an object
  • Fatal Python error: Cannot recover from stack overflow.
In short

A function calls itself more than about 1000 times, Python’s default limit. Most often the base case is never reached, or a property or __getattr__ accidentally calls itself. Fix the stop condition or rewrite the function iteratively; raising the limit is only a last resort.

Be the first to confirm this fix

What this error means

Each function call pushes a frame onto the call stack. To keep an infinite recursion from crashing the whole process, CPython counts the call depth and raises RecursionError as soon as it exceeds sys.getrecursionlimit(), which is 1000 by default. Python does not optimize tail calls: even a “clean” recursion uses one frame per level. So the error means either endless recursion (a logic bug or a hidden call in an attribute), or a recursive algorithm applied to data that is too deep, such as a very long linked list or deeply nested JSON.

Common causes

  1. Missing or unreachable base case: no stop condition, or an argument that does not move toward it (f(n) instead of f(n - 1), n == 0 never true for a negative or float n).
  2. Property that calls itself: the getter returns self.name or the setter does self.name = value instead of using self._name.
  3. Badly written __getattr__, __setattr__ or __str__: __getattr__ reads an attribute that is not set yet (common with copy or pickle), __setattr__ does self.x = v, __str__ uses f"{self}".
  4. Circular references: recursive serialization of objects that point to each other (parent and children, ORM relationships).
  5. Legitimately deep data: recursive traversal of a tree, graph or list several thousand levels deep.

Step-by-step fix

  1. Read the repeating pattern in the traceback

    Python condenses the repetition into a [Previous line repeated 996 more times] line. The lines just above show the function or functions forming the loop, sometimes two functions calling each other, or a property.

    plaintext
      File "app.py", line 4, in factorial
        return n * factorial(n - 1)
                   ^^^^^^^^^^^^^^^^
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
  2. Check the base case and the progression

    Each recursive call must move the argument closer to the base case, and that case must cover every possible input. Reject invalid inputs explicitly.

    python
    def factorial(n: int) -> int:
        if n < 0:
            raise ValueError("n must be >= 0")
        if n <= 1:  # base case
            return 1
        return n * factorial(n - 1)
  3. Fix properties and special methods

    In a property, store the value in a private attribute (_name). In __getattr__, read state through self.__dict__ and raise AttributeError; in __setattr__, delegate to super().__setattr__().

    python
    class User:
        def __init__(self, name):
            self.name = name
    
        @property
        def name(self):
            return self._name  # not self.name
    
        @name.setter
        def name(self, value):
            self._name = value.strip()  # not self.name = ...
    
    
    class Proxy:
        def __init__(self, target):
            self._target = target
    
        def __getattr__(self, attr):
            target = self.__dict__.get("_target")
            if target is None:
                raise AttributeError(attr)
            return getattr(target, attr)
  4. Rewrite it iteratively

    For deep data, replace recursion with a loop and an explicit stack (a list). Depth is then limited only by memory.

    python
    def walk(root):
        stack = [root]
        while stack:
            node = stack.pop()
            yield node
            stack.extend(reversed(node.children))
    
    
    def fibonacci(n: int) -> int:
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a
  5. Guard serialization against cycles

    When objects reference each other, keep track of objects already visited and return a plain reference instead of descending into them again.

    python
    def to_dict(node, seen=None):
        seen = set() if seen is None else seen
        if id(node) in seen:
            return {"ref": node.id}
        seen.add(id(node))
        return {
            "id": node.id,
            "children": [to_dict(child, seen) for child in node.children],
        }
  6. Last resort: raise the limit

    If the depth is known and bounded (a few thousand levels), you can raise the limit. Beware: a value that is too high can exhaust the C stack, and the process then crashes hard (segmentation fault) with no traceback. Never use it to hide an infinite recursion.

    python
    import sys
    
    print(sys.getrecursionlimit())  # 1000 by default
    sys.setrecursionlimit(5000)

Did this fix work for you?

Confirm it in one click: it will rise for the next developers stuck on the same error.

Keep it from coming back

  • Write the base case first in every recursive function and test it with edge values (0, negative, empty).
  • Prefer a loop whenever depth depends on external data (files, JSON, user-built trees).
  • In properties and __getattr__/__setattr__ methods, never access the public attribute you are defining.

Frequently asked questions

What is the default recursion limit in Python?

1000 nested calls, visible with sys.getrecursionlimit(). In practice the error happens slightly earlier, because your code does not start at depth zero.

Does @functools.cache prevent RecursionError?

No, not on the first call: memoization reduces the number of calls, but fib(5000) still goes 5000 levels deep. For large values, use an iterative version.

Does Python optimize tail recursion?

No. CPython does not eliminate tail calls, so a tail-recursive function uses as much stack as any other. Turn it into a while loop.

Useful tools for this error

More Python errors

All Python errors →