Sub topic 2
How the Call Stack Runs Recursive Calls
This chapter assumes you can write and call Python functions, read if statements and loops, and follow a short program by hand. You should also know what a base case and a recursive case are, since the previous chapter covered them. This chapter shows what Python actually does when a function calls itself. Once you have this model, recursive code becomes something you can trace and predict line by line.
The working model: one frame per call
Each function call gets its own stack frame. A stack frame is a block of memory that holds everything that one call needs while it runs. The call stack is the ordered pile of all frames that are active right now. The frame on top belongs to the call that is currently running. Every frame below it belongs to a call that is paused while it waits for the call above it to return.
A recursive call is handled the same way as any other call. Python does not treat "a function calling itself" as a special case. It pushes a new frame, runs the function body in that frame, and pops the frame when the body returns.
| Part of a frame | What it holds | Why it matters for recursion |
|---|---|---|
| Parameters | The argument values for this call, such as `n = 2` | Each call has its own `n`, so values from different calls never overwrite each other |
| Local variables | Names assigned inside the body, such as `result` | Locals are private to the frame |
| Return point | The place in the caller where execution resumes | After a call returns, its caller continues from the middle of an expression |
| Pending work | The partly evaluated expression, such as `n + ⟨waiting⟩` | This work is finished during unwinding, after the inner call returns |
The last row is the one most people miss. When Python evaluates n + sum_to(n - 1), it has already read n. It then pauses the whole expression until sum_to(n - 1) returns a value.
A running example
The example in this chapter adds the integers from 1 to n. It is small enough to trace completely, and it has the same shape as factorial, which the next chapter covers.
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1)
print(sum_to(4)) # 10The call sum_to(4) cannot finish until it knows sum_to(3). That call needs sum_to(2), and so on down to sum_to(0), which returns immediately. Then the answers flow back up.
Winding and unwinding
A recursive computation runs in two phases.
- Winding. The calls go deeper. Each call pushes a new frame and pauses at its recursive call. The stack grows until a call reaches the base case.
- Unwinding. The base case returns a value. Its frame is popped, and the frame below resumes with that value, finishes its pending work, and returns. This repeats until the original frame returns.
The same process can be drawn as a series of stack snapshots. The top of the stack is on the left of each snapshot.
At its tallest, the stack holds n + 1 frames for sum_to(n). This count is the function's recursion depth, and it determines how much stack memory the function uses. A later chapter explains what happens when the depth gets too large.
Tracing with indentation
You can make the stack visible by passing the depth along and indenting the output by that amount.
def sum_to_traced(n, depth=0):
indent = " " * depth
print(f"{indent}call sum_to({n})")
if n == 0:
print(f"{indent}return 0")
return 0
result = n + sum_to_traced(n - 1, depth + 1)
print(f"{indent}return {result}")
return result
sum_to_traced(3)Output:
call sum_to(3)
call sum_to(2)
call sum_to(1)
call sum_to(0)
return 0
return 1
return 3
return 6Each indentation level is one frame. A call line and its matching return line sit at the same indentation, and everything between them happened while that frame was paused. This technique is worth keeping in mind whenever a recursive function gives an answer you did not expect.
Work before and after the recursive call
Where you put code relative to the recursive call decides when it runs. Code before the call runs during winding, from the outermost call inward. Code after the call runs during unwinding, from the innermost call outward.
def down_up(n):
if n == 0:
print("base")
return
print("down", n)
down_up(n - 1)
print("up", n)
down_up(3)Output:
down 3
down 2
down 1
base
up 1
up 2
up 3The "up" lines appear in reverse order because the stack is last-in, first-out. The frame for n = 1 was pushed last, so it is the first one to resume. Many recursive algorithms rely on this reversal, for example printing a linked list backwards or building a result from the smallest piece upward.
Seeing real frames
You do not have to take the frame model on trust. Python's inspect module can count the frames on the stack.
import inspect
def depth_probe(n):
if n == 0:
return len(inspect.stack())
return depth_probe(n - 1)
baseline = depth_probe(0)
print(depth_probe(5) - baseline) # 5depth_probe(5) reaches the base case with five more frames on the stack than depth_probe(0) does. The baseline subtraction removes the frames that belong to the interpreter and the module, so the result is the same however you run the script.
A traceback shows the same thing. When an exception is raised deep in a recursion, Python prints one entry per active frame:
def explode(n):
if n == 0:
raise RuntimeError("hit the base case")
return explode(n - 1)
explode(3)The traceback lists the line return explode(n - 1) three times, once for each of n = 3, 2, 1, and then the raise line for n = 0. A traceback is a printout of the call stack at the moment of failure.
Common errors
Assuming calls share variables
Each frame has its own copy of n and its own locals. Assigning n = 99 inside one call has no effect on the caller's n. If you need information to flow between calls, pass it as an argument or return it.
Forgetting to return the recursive result
def sum_to_broken(n):
if n == 0:
return 0
n + sum_to_broken(n - 1) # value computed, then thrown away
print(sum_to_broken(1)) # NoneThe base case returns 0, but the frame for n = 1 computes 1 + 0 and discards it. The function then falls off the end and returns None. With sum_to_broken(2), the frame for n = 2 receives that None and evaluates 2 + None, which raises TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'. When a recursive function returns None or fails with a NoneType error, check every path for a missing return.
Expecting the result before unwinding
Nothing is added together during winding. In sum_to, every addition happens on the way back up. If you place a print(result) before the recursive call, result does not exist yet. Ask yourself whether a value is known before or after the inner call returns.
Missing or unreachable base case
If no call ever reaches the base case, frames keep piling up until Python stops the program with RecursionError. A typical cause is a step that skips past the base case, such as calling sum_to(n - 2) with an odd n when the only base case is n == 0. The chapter on depth limits covers the causes and fixes in detail.
Exercises
Exercise
Without running it, what does down_up(2) print, and what is the maximum number of down_up frames on the stack at any moment?
Show answer
It prints "down 2", "down 1", "base", "up 1", "up 2", one per line. The maximum is 3 frames, for n = 2, 1, and 0, all active when "base" is printed.
Exercise
A function is defined as def g(n): return 0 if n == 0 else g(n - 1) + n * 10. Write the pending expression held by each frame of g(3) during winding, then give the value each frame returns during unwinding.
Show answer
During winding the frames hold n=3: ? + 30, n=2: ? + 20, n=1: ? + 10, and n=0 is the base case. During unwinding g(0) returns 0, g(1) returns 0 + 10 = 10, g(2) returns 10 + 20 = 30, and g(3) returns 30 + 30 = 60.
Exercise
Change sum_to so it prints each value of n in increasing order (0, 1, 2, ..., n) while still returning the correct sum. Where must the print go, and why?
Show answer
Put the print after the recursive call, for example result = n + sum_to(n - 1), then print(n), then return result, and add print(0) in the base case before return 0. Code after the recursive call runs during unwinding, and frames resume from the deepest (smallest n) outward, so the values come out in increasing order.