Sub topic 6
Moving through the call stack: where, up, down
When pdb stops your program, the line it shows is only the innermost point of a chain of function calls. The cause of a bug often sits in a caller, such as a function that passed in a bad value. This chapter covers how to see that chain and inspect any frame in it.
This chapter assumes you can start a pdb session with breakpoint(), use p and n, and read a traceback. These are covered in earlier chapters.
What the call stack is
Each time a function runs, Python creates a frame. A frame holds that call's local variables, its arguments, and the line currently executing. When report() calls total(), which calls parse_price(), three frames are active at once, plus the frame for the module's top-level code. Together they form the call stack.
pdb always has one selected frame, also called the current frame. The commands p, pp, args, list, and display all work on that frame. When a session starts, the selected frame is the innermost one, where execution stopped. The commands in this chapter change the selected frame. They do not change where the program is running.
A program to explore
Save this as prices.py:
def parse_price(text):
if not text.startswith("$"):
breakpoint()
return float(text.strip("$"))
def total(items):
result = 0.0
for item in items:
result += parse_price(item)
return result
def report(items):
amount = total(items)
print(f"Total: {amount}")
report(["$3.50", "$4.25", "n/a"])The guard on line 2 means pdb stops only for the bad item "n/a". Run python prices.py. The first two items parse normally, and pdb opens on the third:
> /tmp/prices.py(4)parse_price()
-> return float(text.strip("$"))
(Pdb)The path on your machine will differ. The > line shows the selected frame: the file, the line number in parentheses, and the function name. The -> line shows the source line about to run.
where: see the whole stack
The where command prints every frame, and w is the short form. bt is an alias, short for "backtrace".
(Pdb) w
/tmp/prices.py(19)<module>()
-> report(["$3.50", "$4.25", "n/a"])
/tmp/prices.py(15)report()
-> amount = total(items)
/tmp/prices.py(10)total()
-> result += parse_price(item)
> /tmp/prices.py(4)parse_price()
-> return float(text.strip("$"))Three things to read here:
- Order. The oldest frame is at the top and the newest at the bottom. This matches a traceback, where the most recent call is last.
- The
>marker. It marks the selected frame, not necessarily the innermost one. After you move withup, the marker moves with you. - Line numbers. For every frame except the innermost, the number is the line that is currently making a call. Line 10 in
totalis the call that has not returned yet.
up and down: change the selected frame
The directions follow the age of the frames:
up(u) moves to the caller, which is an older frame and higher in thewlisting.down(d) moves back toward the innermost frame.
(Pdb) u
> /tmp/prices.py(10)total()
-> result += parse_price(item)
(Pdb) p item
'n/a'
(Pdb) p result
7.75
(Pdb) u
> /tmp/prices.py(15)report()
-> amount = total(items)
(Pdb) p items
['$3.50', '$4.25', 'n/a']
(Pdb) d
> /tmp/prices.py(10)total()
-> result += parse_price(item)This is the point of the commands. Inside parse_price you only see text, and nothing there says where "n/a" came from. One level up, you see the loop variable and the running total. Two levels up, you see the original list. The bad value is in the input to report(), so the fix belongs at the data source or in a validation step, not in parse_price.
Both commands accept a count. u 2 goes up two frames at once, and d 2 goes down two. Moving past either end prints a message and changes nothing:
(Pdb) u 10
> /tmp/prices.py(19)<module>()
-> report(["$3.50", "$4.25", "n/a"])
(Pdb) u
*** Oldest frameThe Python documentation says the count form is available. The Oldest frame and Newest frame messages are the signal that you hit a boundary.
Inspecting from another frame
Once you have moved, every inspection command applies to the selected frame.
| Command | Effect in the selected frame |
|---|---|
| `p expr`, `pp expr` | Evaluates the expression using that frame's variables |
| `a` or `args` | Prints that function's arguments |
| `l` | Lists source around that frame's current line |
| `ll` | Lists the whole function containing that frame's line |
| `pp locals()` | Prints every local variable of that frame |
| `display expr` | Re-evaluates the expression whenever the selected frame changes or you step |
In the total frame, ll shows the entire function and marks the line that is waiting on a call:
(Pdb) u
> /tmp/prices.py(10)total()
-> result += parse_price(item)
(Pdb) ll
7 def total(items):
8 result = 0.0
9 for item in items:
10 -> result += parse_price(item)
11 return resultUse pp locals() when you do not yet know which variable matters. It is a quick way to compare what each caller held at the moment of the call.
Stepping and the selected frame
Moving with up does not move the program. Execution is still paused inside parse_price. Stepping and resuming commands also still act on the running program. c continues from where the program stopped, no matter which frame you selected.
The line-based stepping commands are less obvious. In CPython's pdb, n, unt, and r are tied to the selected frame. If you go up into total and type n, pdb runs until execution reaches the next line in total. That lets you finish the inner call and stop in the caller. s is different, because it stops at the very next line of Python code in any frame. If the behavior surprises you, run w first and check where the > marker is.
Common errors
- Typing
uwhen you meant to step. Nothing runs. You only moved the view. Check the>marker inwbefore you assume the code advanced. - Confusing the direction.
upmeans older, which is the caller. It does not mean "toward the top of the source file". - Shadowed command names. If a variable is named
u,d,w,n, orc, typing its name runs the command. Usep uor!uto print the variable. - Hunting through framework frames. In a web app or test runner,
wcan print dozens of frames from library code. Find your own files in the listing, then useu Nwith that distance. - Expecting dead frames.
whereshows only frames that are still active. A function that already returned has no frame to inspect. Add a breakpoint earlier if you need its locals, or userto run to the end of the current function and see its return value.
Using the stack with post-mortem debugging
The same commands work after a crash. In post-mortem mode, the stack is the traceback of the exception, and the selected frame starts at the frame that raised. Use w to see the chain of calls that led to the error, then u to examine each caller. The next chapters on post-mortem debugging build on this.
Exercise
You are stopped in parse_price with the stack shown above. You want to know how many items report was given. Which commands do you type, and does the program advance?
Show answer
Type u 2 (or u twice) to select the report frame, then p len(items). For the example list the result is 3. The program does not advance, because up only changes the selected frame. Type d 2 to return to the innermost frame, or check with w, where the > marker shows the selected frame.
Exercise
In w output, the parse_price frame is at the bottom and the module frame is at the top. Which command moves from parse_price toward the module frame, and what message do you get when you can go no further?
Show answer
up (or u) moves toward the module frame, because that frame is the oldest. At the end, pdb prints *** Oldest frame and leaves the selected frame unchanged.