Sub topic 5
Recursion Depth Limits and Stack Overflow
This chapter assumes you can read Python functions, know that each call pushes a stack frame (covered in the call stack chapter), and have seen the recursive factorial from earlier chapters. You will learn why deep recursion fails, what Python does to prevent a crash, and how to choose between raising the limit and rewriting the code as a loop.
Why the Stack Has a Ceiling
Every active call needs a stack frame. A frame holds the call's local variables, its arguments, and the point to return to. The memory for frames is finite. Two separate limits apply:
- The interpreter's recursion limit. CPython counts how many Python frames are active. If the count passes a configured number, it raises
RecursionError. The default is 1000. - The real stack of the operating system thread. This is a fixed block of memory, often 8 MB for the main thread on Linux and less on some other platforms. If native code (C code inside the interpreter or an extension) uses up this block, the process crashes with a segmentation fault or a "stack overflow" error. A crash like this cannot be caught.
The recursion limit is a guard that sits in front of the real stack. Python raises a catchable exception well before the hardware limit is reached, so a runaway recursion fails cleanly instead of killing the process.
Seeing the Limit in Action
The recursive factorial needs one frame per value from n down to 0, so its depth is about n + 1. Anything near 1000 hits the default limit.
import sys
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
print("limit:", sys.getrecursionlimit()) # limit: 1000 (by default)
print(factorial(900).bit_length()) # works: 7462 bits
try:
factorial(5000)
except RecursionError as exc:
print("RecursionError:", exc) # maximum recursion depth exceeded ...The limit counts every frame on the stack, including the frames that were already there before factorial was called. These include the module's top-level code, and in a notebook or test runner they include many framework frames as well. In practice you can never use all 1000 for your own function. factorial(990) might work in a plain script and fail inside pytest.
Measuring Depth Directly
Depth is the length of the longest chain of calls that are active at the same time. It is different from the total number of calls. You can measure depth with a counter that goes up on entry and down on exit:
depth = 0
max_depth = 0
def tracked(fn):
def wrapper(*args):
global depth, max_depth
depth += 1
max_depth = max(max_depth, depth)
try:
return fn(*args)
finally:
depth -= 1
return wrapper
@tracked
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
@tracked
def fast_power(x, n):
if n < 0:
return 1 / fast_power(x, -n)
if n == 0:
return 1
half = fast_power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
fib(20)
print("fib(20) max depth:", max_depth) # 20
max_depth = 0
fast_power(2, 1_000_000)
print("fast_power depth:", max_depth) # 21Naive fib(20) makes 21,891 calls, yet only 20 of them are ever on the stack together. The recursion tree is wide but shallow, and the stack holds only one root-to-leaf path at a time. fast_power halves its exponent at each step, so an exponent of one million needs only about 21 frames.
| Function | Total calls | Maximum depth | Hits default limit at |
|---|---|---|---|
| `factorial(n)` | n + 1 | n + 1 | n ≈ 1000 |
| `factorial_acc(n)` | n + 1 | n + 1 | n ≈ 1000 (CPython has no tail-call elimination) |
| `fib(n)` naive | about 1.6ⁿ | n | runs too slowly long before the depth matters |
| `fib_memo(n)`, empty cache | 2n − 1 | n | n ≈ 500–1000, depending on version |
| `fib_iter(n)` | 1 | 1 | never |
| `power(x, n)` | n + 1 | n + 1 | n ≈ 1000 |
| `fast_power(x, n)` | about log₂ n | about log₂ n | never in practice |
Two rows deserve attention. Memoization fixes the running time of Fibonacci but not its depth. On a fresh cache, fib_memo(n) descends all the way to fib_memo(1) before it returns anything. On Python 3.11 and earlier, the C wrapper from lru_cache can count against the limit too, so failure may come at roughly half the depth you expect. The linear power has the same depth problem as factorial, and squaring removes it as a side effect of removing the extra multiplications.
Option 1: Raise the Limit
sys.setrecursionlimit changes the guard, but it does not make the stack any larger. If the real stack runs out before the new limit is reached, the process crashes. The usual safe pattern runs the deep recursion in a new thread with a larger stack:
import sys
import threading
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
def job():
print(factorial(50_000).bit_length()) # 708355
sys.setrecursionlimit(60_000)
threading.stack_size(256 * 1024 * 1024) # 256 MB for threads created after this call
t = threading.Thread(target=job)
t.start()
t.join()threading.stack_size affects only threads created after the call, which is why the work goes in a new thread instead of the main one. Some platforms reject very large sizes with ValueError.
This approach is reasonable for scripts, contest code, or a one-off computation. It is a poor choice for library code, because the recursion limit is a process-wide setting that your callers did not ask you to change. It also leaves the depth tied to the input. If someone passes an input ten times larger, the code fails again.
Option 2: Rewrite as Iteration
A loop uses constant stack depth, so it removes the problem for good. For linear recursions like factorial and power, the rewrite is mechanical. You accumulate the result in a variable instead of in pending stack frames:
def factorial_iter(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_iter(50_000).bit_length()) # 708355, no limit changes neededWhen the work done after the recursive call is harder to fold into a loop, you can simulate the call stack with an explicit list. The list lives on the heap, which can hold millions of entries. This version follows the two phases of the recursive factorial exactly: it pushes pending work on the way down and multiplies on the way back up.
def factorial_stack(n):
if n < 0:
raise ValueError("n must be non-negative")
pending = []
while n > 0: # descending phase: "call" factorial(n - 1)
pending.append(n)
n -= 1
result = 1 # base case: factorial(0) = 1
while pending: # unwinding phase: each frame multiplies by its n
result *= pending.pop()
return result
print(factorial_stack(5) == 120) # True
print(factorial_stack(20_000) == factorial_iter(20_000)) # TrueThe explicit-stack technique works for any recursion, including tree traversals with several recursive calls. For deep memoized recursion, an easier fix is often to fill the cache in order so that no single call has to go deep:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
for k in range(0, 5001, 200): # each call recurses at most ~200 levels
fib_memo(k)
print(fib_memo(5000).bit_length()) # 3471This warm-up turns the top-down method into something close to bottom-up iteration. Taken to its conclusion, the idea becomes fib_iter, covered in the bottom-up chapter.
Option 3: Change the Algorithm's Shape
Sometimes the right fix is to reduce the depth itself. Divide-and-conquer recursion such as fast_power has logarithmic depth, so it never comes close to the limit. If your recursion peels off one element at a time, check whether it could split the problem in half instead. The Fibonacci chapters use the same reasoning when they move from the call tree to a better algorithm.
Common Errors
- Treating
RecursionErroras proof of a missing base case. Infinite recursion does cause it, but so does correct code given an input that is simply large. Check the base case first, then check the depth. - Raising the limit to a huge value "just in case."
sys.setrecursionlimit(10**9)turns a clean exception into a possible segmentation fault, especially on Python 3.10 and earlier or when C extensions are involved. - Assuming memoization makes recursion safe. Memoization reduces the number of calls. It does not reduce the depth of the first call on an empty cache.
- Catching
RecursionErrorand continuing as normal. The exception can be raised in the middle of an update, leaving data partly modified. Treat it as a bug signal, not as a control-flow tool. - Expecting an accumulator to save stack in Python.
factorial_accis still one frame per call, because CPython does not eliminate tail calls. The next chapter explains why.
Exercise
A recursive function count_down(n) prints n and calls count_down(n - 1) until n is 0. Called from a plain script, count_down(995) works but count_down(995) fails when run inside a test framework. Explain why, and name two fixes that do not involve changing the recursion limit.
Show answer
The recursion limit counts every frame on the stack, including the frames the test framework already has active. Under the framework, the extra frames push the total past 1000. Fixes: rewrite count_down as a for or while loop, which uses constant depth, or simulate the calls with an explicit list. Either one removes the dependence on how many frames sit underneath.
Exercise
Without running code, give the maximum recursion depth of fast_power(3, 2**40) and of power(3, 2**40), and say which one raises RecursionError under the default limit.
Show answer
fast_power halves the exponent each call: 240, 239, ..., 1, 0. That is 42 frames, roughly log2(n) + 2, so it is well under the limit (computing the enormous result is another matter). power decrements by one each call, so it would need about 2**40 frames. It raises RecursionError after roughly 1000 calls.
Exercise
Calling fib_memo(3000) on an empty cache raises RecursionError, but after fib_memo(1500) has run once, fib_memo(3000) succeeds. Why?
Show answer
After the first call, values 0 through 1500 are in the cache. The second call recurses from 3000 down only until it reaches 1500, a cached value, so its depth is about 1500 instead of 3000. That depth can fit under a limit that 3000 cannot. Each cached value acts as a new base case, and that is why filling the cache in increasing order works.