Sub topic 4
How the Call Stack Runs Recursive Calls
This chapter assumes you can write and call Python functions, read conditionals, and recognize a base case and a recursive case in a function like factorial. Here you will see what Python does when a function calls itself, so that recursive code stops looking like a trick.
Every call gets its own frame
When Python calls a function, it creates a stack frame. A stack frame is a block of memory that holds everything one call needs while it runs:
- The function's parameters and local variables for this call only.
- The point in the caller's code to return to when this call finishes (the return address).
- Any partly finished work. In
n * factorial(n - 1), that is the value ofnwaiting to be multiplied.
The call stack is the ordered pile of frames that are currently active. Calling a function pushes a new frame on top. Returning pops the top frame off, and control goes back to the frame underneath. Only the top frame is running at any moment. Every frame below it is paused partway through, waiting for the call it made to return.
A recursive call follows the same rules as any other call. When factorial(3) calls factorial(2), Python does not reuse or overwrite the first call. It pushes a second, separate frame for factorial with its own n. Each frame keeps its own n, so the calls do not interfere with each other.
Watching frames push and pop
The function below is factorial with a depth parameter added. The parameter only controls indentation, so you can see how deep the stack is at each step.
def factorial(n, depth=0):
indent = " " * depth
print(f"{indent}call factorial({n})")
if n == 0:
result = 1
else:
result = n * factorial(n - 1, depth + 1)
print(f"{indent}return {result}")
return result
factorial(3)
# call factorial(3)
# call factorial(2)
# call factorial(1)
# call factorial(0)
# return 1
# return 1
# return 2
# return 6Read the output from top to bottom. Each call line is a push, and the indentation grows. Each return line is a pop, and the indentation shrinks. The returns come out in the opposite order from the calls. The last frame pushed, factorial(0), is the first to finish. This order is called last in, first out (LIFO), and it is why the structure is called a stack.
Snapshots of the stack
Another way to picture the stack is to freeze it at chosen moments. In the table below, the top of the stack is on the left.
| Moment | Stack (top first) | What the top frame is doing |
|---|---|---|
| Just after `factorial(3)` starts | f(3) | Checking whether n == 0 |
| f(3) has called f(2) | f(2), f(3) | f(3) is paused, holding n=3 |
| Base case reached | f(0), f(1), f(2), f(3) | Returning 1 |
| f(0) has returned | f(1), f(2), f(3) | Computing 1 * 1 |
| f(1) and f(2) have returned | f(3) | Computing 3 * 2 |
| All calls done | (empty) | Control is back in the caller |
The stack is tallest at the base case. For factorial(n) the stack holds n + 1 frames at that point, so the memory a recursive function needs grows with how deep the recursion goes. That cost is separate from its running time. A later chapter covers what happens when the depth gets too large.
Local variables live and die with their frame
Each frame keeps its own local variables, so a value set before the recursive call is still there after the call returns:
def show(n):
label = f"frame for n={n}"
if n > 0:
show(n - 1)
print(label)
show(2)
# frame for n=0
# frame for n=1
# frame for n=2Each call sets label and then, unless it is the base case, makes a deeper call before printing. The deeper calls create their own label variables and leave the caller's alone. When a frame resumes, its label still holds the value it had. The output runs from n=0 up to n=2 because a frame can only print after every frame above it has popped.
The same idea explains a pattern you will use often. Code before the recursive call runs on the way down, in call order. Code after the recursive call runs on the way back up, in reverse order.
Common errors that come from the stack model
Dropping the return value
A frame hands a value to its caller only through return. If you compute the recursive result and don't return it, the function returns None, and the frame below gets None as its result.
def factorial_bad(n):
if n == 0:
return 1
n * factorial_bad(n - 1) # result computed, then thrown away
try:
print(factorial_bad(3))
except TypeError as e:
print("TypeError:", e)
# TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'Here factorial_bad(1) computes 1 * 1 and then returns None. Its caller, factorial_bad(2), then tries 2 * None and crashes. The bug is in one frame, but the error shows up one frame further down the stack. Remember this when a traceback points at a line that looks correct.
Expecting a return to jump to the top
A return in the base case ends only the top frame. It does not end the whole recursion. Control goes back to the paused caller, which then finishes its own pending work. If the result looks wrong, look at what each caller does with the value it receives.
Reading tracebacks upside down
When an error is raised deep in the recursion, Python prints one traceback entry for each active frame, with the most recent call last. The bottom entry is the frame where the error was raised. The entries above it are the paused callers that led to it. Long runs of identical lines in a traceback mean many recursive frames were on the stack.
Exercise
Without running it, what does this code print? def f(n): if n == 0: return; print("down", n); f(n - 1); print("up", n) followed by f(3)
Show answer
It prints "down 3", "down 2", "down 1", then "up 1", "up 2", "up 3". The lines before the recursive call run as frames are pushed. The lines after it run as frames are popped, in reverse order. The call f(0) returns right away and prints nothing.
Exercise
How many frames for factorial are on the call stack at the moment factorial(5) reaches its base case, and what value of n does each frame hold?
Show answer
There are six frames, holding n = 0, 1, 2, 3, 4, and 5, with n = 0 on top. Each frame except the top one is paused, waiting to multiply its own n by the result of the call above it.
Exercise
A recursive function that sums a list sometimes returns None for lists longer than one element. Using the stack model, what is the most likely bug?
Show answer
The recursive case computes something like items[0] + total(items[1:]) but leaves out the return, or returns only on some branches. Any frame that falls off the end of the function returns None to its caller. That caller then either crashes on None or passes None further down the stack.