Sub topic 4
How the Call Stack Runs Recursive Calls
This chapter assumes you can write and call Python functions and that you know what a base case and a recursive case are. It explains what the interpreter actually does when a function calls itself.
Stack frames
Each function call gets a stack frame, a block of memory that holds that call's parameters, its local variables, and the point to return to when it finishes. Frames live on the call stack. A new call pushes a frame onto the top, and a return pops the top frame off.
Recursion uses no special mechanism. When factorial(3) calls factorial(2), Python pushes a second frame for factorial with its own n. The two frames don't share local variables. Each frame's n stays fixed for the whole life of that call.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(3)) # 6While factorial(0) runs, the stack holds four frames, with n equal to 3, 2, 1, and 0. Each of the three lower frames is paused partway through n * factorial(n - 1). It has its own n and is waiting for the call above it to return a value.
Winding and unwinding
A recursive computation has two phases:
- Winding: calls push frames until one reaches the base case.
- Unwinding: the base case returns, its frame is popped, and each paused frame resumes, finishes its work, and returns to the frame below it.
Code placed before the recursive call runs during winding, in call order. Code placed after it runs during unwinding, in reverse order.
def countdown(n):
if n < 0:
return
print("enter", n)
countdown(n - 1)
print("exit", n)
countdown(2)
# enter 2
# enter 1
# enter 0
# exit 0
# exit 1
# exit 2The exit lines come out in reverse because a frame can't finish until every deeper frame has returned. The stack is last in, first out.
Common errors
| Mistake | What happens on the stack |
|---|---|
| Expecting a variable changed in a deeper call to change the caller's copy | Each frame has its own local variables, so the caller's value stays the same |
| Dropping the result, for example writing `factorial(n - 1)` instead of `return n * factorial(n - 1)` | The returned value is thrown away and the frame returns `None` |
| Missing or unreachable base case | Frames keep being pushed until the depth limit is reached |
Exercise
In countdown(3), how many frames for countdown are on the stack at the deepest point, and which line prints last?
Show answer
Five frames, for n = 3, 2, 1, 0, and -1. The frame for -1 is the base case, which returns right away. The last line printed is "exit 3", because the outermost frame finishes last.
Exercise
Change countdown so that it prints only after the recursive call. In what order do the numbers appear for countdown(2)?
Show answer
They appear as 0, 1, 2, because every print now runs during unwinding, starting from the deepest frame.