RuntimePython Error

RecursionError

RecursionError: maximum recursion depth exceeded in comparison

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    fib(100)
RecursionError: maximum recursion depth exceeded in comparison

What causes this error

A recursive function exceeded the default limit of 1000 frames. Missing base cases, infinite mutual recursion, or algorithms requiring deep recursion are the typical triggers.

How to fix it

Add or fix the base case in recursive functions. Use memoization with @functools.lru_cache. Convert to iterative algorithms. Only increase sys.setrecursionlimit() as a last resort with small increments.

Code that causes this error

Broken
def fib(n):
    return fib(n-1) + fib(n-2)

fib(100)

Fixed code

Fixed
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print(fib(100))

About RecursionError

This error is a specific message variant of RecursionError, often appearing with 'in comparison', 'while calling a Python object', or 'while getting the repr of an object'. The default recursion limit in Python is 1000 (can be checked with `sys.getrecursionlimit()`). This limit exists to prevent stack overflows, which would crash the Python interpreter with a segfault rather than a clean exception.

The 'in comparison' variant appears when __eq__ or __lt__ methods recurse infinitely, which can happen with circular data structures or poorly implemented comparison methods. The 'while getting the repr' variant occurs when __repr__ methods create infinite loops, common with objects that reference each other. The fix depends on the cause: add base cases to recursive functions, use `functools.lru_cache` for memoization, or convert to iterative algorithms.

Common scenarios

1

Infinite recursion from missing or incorrect base cases

2

Modifying dictionaries or sets during iteration

3

Calling generators or coroutines in unsupported ways

4

Using asyncio event loops incorrectly or attempting to nest them

Related errors