Reproduce, capture the traceback, find the cycle, then convert recursion to iteration or raise the limit deliberately
RecursionError is raised when the interpreter exceeds sys.getrecursionlimit() during a call. Intermittent cases usually mean the recursion depth depends on input size or on a rare data shape such as a cycle in a graph or a self-referential object. The first step is to capture the traceback, because the repeated frame in the traceback points directly at the recursive function. Then reproduce with the smallest input that triggers it. The fix is almost always to convert the recursion into an explicit stack or a loop, because raising the limit increases the risk of a C stack overflow that crashes the process hard instead of raising a clean Python error. Only raise the limit if you have measured that the depth is bounded and the process can afford the stack.
Read the traceback: the frame that repeats is the recursion site. That is your starting point.
Check for cycles: a self-referential structure or a graph with a back edge will recurse forever.
Reproduce with minimal input, then reduce further until the trigger is obvious.
Prefer converting to an iterative algorithm with an explicit stack. It is bounded and predictable.
If you must raise the limit, do it in the entry point and treat it as a temporary measure, not a fix.
Common mistake: raising sys.setrecursionlimit(100000) and then seeing a segmentation fault instead of a clean error.
Version note: sys.setrecursionlimit exists in all versions, and 3.12 improved some recursion-related error messages, but the underlying C stack risk is unchanged.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience