Last modified: Feb 10, 2026 By Alexander Williams
Fix RecursionError: Maximum Depth Exceeded in Python
You are writing a Python program. Suddenly, it crashes. The error message says "RecursionError: maximum recursion depth exceeded while calling a Python object." This is a common but confusing error for beginners. This article will explain what it means and how to fix it.
What is a RecursionError?
A RecursionError happens when a function calls itself too many times. Python has a safety limit to prevent a crash from infinite recursion. This limit is called the recursion depth. The default maximum depth is 1000 calls.
When your recursive function exceeds this limit, Python stops it. It raises the RecursionError to protect your program. This prevents it from using all your computer's memory and crashing your system.
What Causes This Error?
The main cause is a recursive function without a proper base case. A base case is the condition that stops the recursion. Without it, the function calls itself forever.
Another cause is a recursive function that needs more than 1000 calls to solve a problem. Some algorithms, like tree traversals on deep data, can hit this limit. This is especially true when dealing with complex Python Objects in Objects or deeply nested structures.
A Simple Example of the Error
Let's look at a classic example: a countdown function. This function is meant to count down from a number to zero.
def countdown(n):
print(n)
# This is the recursive call
countdown(n - 1)
# This will cause the error
countdown(5)
5
4
3
2
1
0
-1
-2
...
RecursionError: maximum recursion depth exceeded while calling a Python object
The function prints numbers but never stops. It lacks a base case to tell it when n is small enough. It will try to count down forever, quickly hitting the recursion limit.
How to Fix the Error: Add a Base Case
The first and best fix is to ensure your recursive function has a correct base case. The base case is the condition where the function returns a value without calling itself again. It stops the recursion.
Here is the corrected countdown function.
def countdown(n):
# This is the BASE CASE
if n <= 0:
print("Blastoff!")
return # Stop the recursion here
print(n)
# Recursive call with a smaller problem
countdown(n - 1)
countdown(5)
5
4
3
2
1
Blastoff!
The key line is if n <= 0:. This is the base case. When n is 0 or less, the function prints "Blastoff!" and returns. It does not call countdown again. This prevents infinite recursion.
Solution 2: Increase the Recursion Limit
Sometimes, your algorithm is correct but needs more depth. You can increase Python's recursion limit using the sys.setrecursionlimit() function.
Use this method with extreme caution. Setting the limit too high can cause a real program crash if there is a bug. It can also lead to a segmentation fault on your operating system.
import sys
# Increase the recursion limit to 2000
sys.setrecursionlimit(2000)
def recursive_func(depth):
if depth <= 0:
return depth
return recursive_func(depth - 1)
# This would fail with the default limit of 1000
print(recursive_func(1500))
This approach is a temporary fix. It does not solve a flawed algorithm. It only gives you more room. Always try to fix the logic first.
Solution 3: Convert Recursion to Iteration
The most robust solution is to avoid deep recursion altogether. You can often rewrite a recursive function using a loop. This is called an iterative solution.
Iterative solutions use a loop like for or while. They manage state with variables instead of call stacks. They are generally more efficient and avoid recursion limits.
Here is the countdown function written iteratively.
def countdown_iterative(n):
while n > 0:
print(n)
n = n - 1
print("Blastoff!")
countdown_iterative(5)
This function does the same job. It will never raise a RecursionError, no matter how large n is. For complex data structures, understanding Python Objects: Classes, Instances, and Methods can help you design better iterative logic.
Common Scenarios and Debugging Tips
You might see this error in specific situations. Here are two common ones.
1. Recursive __repr__ or __str__ Methods
If you define a custom class where two instances reference each other, their string representation can cause infinite recursion. This is common in linked lists or tree nodes.
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
# DANGER: This calls repr() on self.next, which is another Node
return f"Node({self.value}, next={repr(self.next)})"
# Create two linked nodes
node_a = Node(1)
node_b = Node(2)
node_a.next = node_b
node_b.next = node_a # Creates a cycle!
# Printing node_a will cause RecursionError
# print(node_a)
The __repr__ method tries to represent node_a.next (which is node_b). Then it tries to represent node_b.next (which is node_a again). This creates an infinite loop. The fix is to avoid calling repr() on a linked object in this way.
2. Recursive Data Serialization
When serializing objects to JSON, you may encounter this error if objects reference each other. Python's default JSON serializer cannot handle circular references. You need custom serialization logic. For guidance, see our JSON Serialization Guide for Custom Python Objects.
Best Practices to Avoid RecursionError
Follow these tips to write safe recursive code.
- Always define a base case first. Before writing the recursive call, write the condition that stops it.
- Ensure progress toward the base case. Each recursive call should modify the arguments to get closer to the stopping condition.
- Prefer iteration for simple loops. If a problem can be solved easily with a
forloop, use that instead of recursion. - Test with small inputs. See if your function terminates correctly with small numbers before using large ones.
- Use a debugger or print statements. Track the arguments of each call to see if they are moving toward the base case.
Conclusion
The "RecursionError: maximum recursion depth exceeded" is Python's way of protecting your program. It signals that a recursive function has called itself too many times. The primary fix is to add a proper base case to your function. If your algorithm is correct but needs more depth, you can use sys.setrecursionlimit() carefully. For the most reliable code, consider converting the recursive logic into an iterative loop using while or for. By understanding recursion and its limits, you can write more robust and efficient Python programs.