Fix "RecursionError: maximum recursion depth exceeded" in Python
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.
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.
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
- Missing or unreachable base case: no stop condition, or an argument that does not move toward it (
f(n)instead off(n - 1),n == 0never true for a negative or floatn). - Property that calls itself: the getter returns
self.nameor the setter doesself.name = valueinstead of usingself._name. - Badly written
__getattr__,__setattr__or__str__:__getattr__reads an attribute that is not set yet (common withcopyorpickle),__setattr__doesself.x = v,__str__usesf"{self}". - Circular references: recursive serialization of objects that point to each other (parent and children, ORM relationships).
- Legitimately deep data: recursive traversal of a tree, graph or list several thousand levels deep.
Step-by-step fix
-
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.File "app.py", line 4, in factorial return n * factorial(n - 1) ^^^^^^^^^^^^^^^^ [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded -
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.
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) -
Fix properties and special methods
In a property, store the value in a private attribute (
_name). In__getattr__, read state throughself.__dict__and raiseAttributeError; in__setattr__, delegate tosuper().__setattr__().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) -
Rewrite it iteratively
For deep data, replace recursion with a loop and an explicit stack (a list). Depth is then limited only by memory.
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 -
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.
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], } -
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.
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
- Fix "ModuleNotFoundError: No module named" in Python
- Fix "IndentationError: unexpected indent" in Python
- Fix "'NoneType' object is not subscriptable" in Python
- Fix "error: externally-managed-environment" with pip
- Fix "UnicodeDecodeError: 'utf-8' codec can't decode byte" in Python
- Fix "KeyError" in Python (dict, pandas, os.environ)
- Fix "attempted relative import with no known parent package" in Python