Sub topic 5
Recursion Depth Limits and Stack Overflow
This chapter assumes you can write recursive functions in Python, such as the recursive factorial. It also assumes you know that each call gets its own stack frame on the call stack. The question here is what happens when the stack gets too deep.
Every Call Costs a Frame
When factorial(n) runs, it cannot finish until factorial(n - 1) returns. That call waits for factorial(n - 2), and so on down to the base case. At the deepest point, n + 1 frames sit on the stack at once. Each frame holds the call's local variables and return address.
Stack memory is limited. If recursion goes deep enough, the program runs out of it. In languages like C, this is a stack overflow, and the process usually crashes. Python protects you with a counter. Once the number of nested Python calls passes a fixed limit, Python raises RecursionError before the real stack runs out.
Seeing the Limit in Practice
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(sys.getrecursionlimit()) # usually 1000
print(factorial(500) > 0) # True: well under the limit
try:
factorial(5000)
except RecursionError as e:
print("RecursionError:", e)The default limit is usually 1000. The input that fails is a little smaller than that, because frames for the interpreter and your own calling code already sit on the stack.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Missing or unreachable base case | Infinite recursion ends in `RecursionError` | Check that every path reaches the base case |
| Recursive step does not shrink the input | Same as above, e.g. `factorial(n)` calling `factorial(n)` | Make sure each call moves toward the base case |
| Negative input with no guard | `factorial(-1)` recurses forever | Validate input, as the `ValueError` check does |
| Correct code with large input | `RecursionError` on valid data | Raise the limit carefully or rewrite as a loop |
The first three rows are bugs. The fourth is a design limit, so the fix is different.
Raising the Limit
You can call sys.setrecursionlimit to allow deeper recursion:
import sys
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
sys.setrecursionlimit(20000)
result = factorial(10000)
print(result.bit_length()) # 118459This example prints bit_length() instead of the number itself. Python 3.11 and later refuse to convert integers with more than 4300 digits to strings by default.
Converting to Iteration
The most reliable fix is to remove the recursion. Factorial makes one recursive call per step, so a loop that carries the running product does the same work with a fixed number of frames:
def factorial_iter(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_iter(10000).bit_length()) # 118459This version works for any n your memory can hold, with no limit to adjust. A good rule is to keep recursion when the depth grows slowly, such as logarithmically in the input, and to use a loop when the depth grows linearly with input size.
Exercise
A recursive function sumto(n) returns n + sumto(n - 1) with base case sumto(0) = 0. With the default limit of 1000, does sumto(900) succeed, and does sum_to(2000)? What is the safest fix for large n?
Show answer
sumto(900) succeeds, because it needs about 901 frames plus a few already on the stack, which stays under 1000. sumto(2000) raises RecursionError. The safest fix is to rewrite it as a loop (or use the formula n * (n + 1) // 2), because raising the limit can still crash the interpreter on some versions.
Exercise
Why does a call like fast exponentiation's fast_power(2, 106) not hit the recursion limit, while power(2, 106) does?
Show answer
fast_power halves the exponent each call, so its depth is about log2(10**6), roughly 20 frames. The linear power function subtracts 1 each call, so it needs about a million frames, far past the limit.