Sub topic 4
Tracing a Recursive Call Step by Step
This chapter assumes you can read Python functions, know what a base case and a recursive case are, and have seen how each call gets its own stack frame on the call stack. Here you put those ideas to work. You will trace recursive calls by hand, then with code that prints the trace for you. You will also learn to read a trace well enough to find bugs.
Tracing means writing down each call, the arguments it received, and the value it returned, in the order these events happen. When a recursive function gives a wrong answer or never stops, a trace is usually the quickest way to see why.
The Two Phases of a Linear Recursion
A function that makes one recursive call per invocation runs in two phases:
- Winding. Each call checks the base case, fails, and makes a smaller call. Every call that is waiting keeps its own frame, with its own
nand the operation it still has to finish. - Unwinding. The base case returns a value. Each waiting frame then finishes its pending operation and returns to its caller, in the reverse of the order in which the calls were made.
Here is the factorial function we will trace:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(4)) # 24The line return n * factorial(n - 1) cannot finish when it is first reached. Python has to evaluate factorial(n - 1) before it can multiply, so the multiplication stays pending in the current frame. Beginners lose track of this pending work more than anything else when tracing by hand.
Tracing by Hand with Substitution
The substitution method rewrites each call as its body until only arithmetic remains:
factorial(4)
= 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * (1 * factorial(0))))
= 4 * (3 * (2 * (1 * 1)))
= 4 * (3 * (2 * 1))
= 4 * (3 * 2)
= 4 * 6
= 24The expression gets wider while the calls wind, because each level adds a pending n *. It gets narrower while they unwind. How wide it gets matches the deepest the call stack goes, which here is five frames for factorial(4).
Tracing with a Frame Table
Substitution gets hard to manage once a function has local variables or several statements. A frame table holds more information. Give each call its own row, and fill in the return value only when that call actually returns.
| Step | Event | Frame | `n` | Pending work | Value |
|---|---|---|---|---|---|
| 1 | call | factorial(4) | 4 | `4 * ?` | |
| 2 | call | factorial(3) | 3 | `3 * ?` | |
| 3 | call | factorial(2) | 2 | `2 * ?` | |
| 4 | call | factorial(1) | 1 | `1 * ?` | |
| 5 | call | factorial(0) | 0 | none (base case) | |
| 6 | return | factorial(0) | 0 | 1 | |
| 7 | return | factorial(1) | 1 | `1 * 1` | 1 |
| 8 | return | factorial(2) | 2 | `2 * 1` | 2 |
| 9 | return | factorial(3) | 3 | `3 * 2` | 6 |
| 10 | return | factorial(4) | 4 | `4 * 6` | 24 |
Each frame has its own n. When factorial(2) returns, the n in factorial(3)'s frame is still 3. The recursive call did not overwrite it. If you keep a single "current n" in your head while tracing, you will get the wrong answer.
The diagram below shows the same events as messages between frames.
Work Before and After the Recursive Call
Where a statement sits relative to the recursive call decides whether it runs while the calls wind or while they unwind. This function prints on both sides of its call:
def countdown(n):
if n == 0:
print("base case")
return
print("before", n)
countdown(n - 1)
print("after", n)
countdown(3)Output:
before 3
before 2
before 1
base case
after 1
after 2
after 3The "before" lines appear in call order, from 3 down to 1. The "after" lines appear in reverse order, because each one runs only once the deeper calls have returned. This is how a recursive function can reverse a sequence without building a reversed copy: do the work after the call. When you trace, put each statement into one of these two groups first.
Automating the Trace
Hand tracing works well for small inputs. For larger ones, have the program print its own trace. The decorator below wraps a function, prints each call and return, and indents the lines by depth so the nesting is visible.
import functools
def trace(func):
depth = 0
@functools.wraps(func)
def wrapper(*args):
nonlocal depth
indent = " " * depth
arg_text = ", ".join(repr(a) for a in args)
print(f"{indent}call {func.__name__}({arg_text})")
depth += 1
try:
result = func(*args)
finally:
depth -= 1
print(f"{indent}return {result!r}")
return result
return wrapper
@trace
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
factorial(3)Output:
call factorial(3)
call factorial(2)
call factorial(1)
call factorial(0)
return 1
return 1
return 2
return 6Every return line has the same indentation as its matching call line, so you can pair them up by eye. The try/finally block resets the depth even if a call raises an exception. Without it, the indentation would be wrong for any later calls after an error.
The decorator works with any number of positional arguments, so you can reuse it on functions with several parameters. It will also work on functions that make more than one recursive call, which a later chapter covers.
Using a Trace to Find Bugs
A trace shows a bug as a pattern you can see. Here are three common ones.
The base case is never reached
def halve_to_zero(n):
if n == 0:
return 0
return halve_to_zero(n - 2)
print(halve_to_zero(4)) # 0
# halve_to_zero(5) recurses until RecursionErrorA trace of halve_to_zero(5) shows the arguments 5, 3, 1, -1, -3, and so on. The argument skips over 0 and the calls never stop. The fix is a base case that covers every value that can end the recursion, such as if n <= 0. As a rule, check that every possible argument sequence lands on a base case. Checking only the sequence your test input produced is not enough.
The returned value is thrown away
def count_items(items):
if not items:
return 0
count_items(items[1:]) # bug: result discarded
return 1
print(count_items([7, 8, 9])) # prints 1, expected 3In the trace, the inner calls return values, but the outer call's return value never depends on them. When a return value appears in the trace and the caller never uses it, look for a missing return or a missing combination step. The fix is return 1 + count_items(items[1:]).
Shared mutable state between frames
Frames do not share local variables, but they can share one object. A default argument such as out=[] is created once, when the function is defined, and every call that relies on the default uses that same list. A trace shows the list keeps growing across separate top-level calls. The standard fix is to use out=None and create a new list inside the function.
Common Tracing Mistakes
| Mistake | What it looks like | Correction |
|---|---|---|
| Losing pending work | Reporting `factorial(4)` as 1 | Write the pending operation in each frame's row |
| One shared `n` | Treating `n` as changing in place | Give each frame its own column of locals |
| Wrong return order | Expecting the outer call to finish first | Returns happen last-in, first-out |
| Ignoring post-call statements | Missing the "after" output | Sort statements into before-call and after-call groups |
| Testing one input only | Missing the skipped base case for odd `n` | Trace an even and an odd input, plus the empty or zero case |
Exercise
Without running it, write the exact output of mystery(3) and its return value.
def mystery(n):
if n <= 0:
return 0
print("in", n)
r = n + mystery(n - 2)
print("out", n, r)
return r
Show answer
The calls go mystery(3), mystery(1), mystery(-1). The output is "in 3", "in 1", then "out 1 1" (1 + 0), then "out 3 4" (3 + 1). The return value is 4. The "in" lines follow call order and the "out" lines follow return order. Because the base case is n <= 0, the argument -1 still stops the recursion.
Exercise
Apply the trace decorator to def power(b, e): return 1 if e == 0 else b * power(b, e - 1) and call power(2, 3). How many call lines are printed, how deep is the deepest indentation, and what does each return line show?
Show answer
Four call lines are printed: power(2, 3), power(2, 2), power(2, 1), and power(2, 0). The deepest line, for power(2, 0), has three levels of indentation (six spaces). The return lines, from innermost to outermost, show 1, 2, 4, and 8.
Exercise
A recursive function produces the right answer for the input [1, 2, 3] but raises IndexError for []. What would you look for in a trace, and what is the likely cause?
Show answer
Trace the call with []. The trace will probably show the very first call trying to access items[0] before any base case runs. The base case is probably written as len(items) == 1, so it never covers the empty list. Changing the base case to handle the empty list (if not items) fixes the error and covers every input, because each recursive call shortens the list until it is empty.