Sub topic 9
Automating breakpoints with commands
This chapter assumes you can start a pdb session with breakpoint() or python -m pdb. It also assumes you can set a breakpoint with b and move around with n, s, and c. If a breakpoint number or the (Pdb) prompt is unfamiliar, review the earlier chapters on breakpoints first.
The problem: stopping too often
A breakpoint inside a loop stops on every iteration. If you only want to see one value per pass, you type p x and c hundreds of times. That is slow, and you lose track of what you were looking for.
The commands command fixes this. It attaches a list of pdb commands to a breakpoint. Each time the breakpoint is hit, pdb runs the list for you. A breakpoint with a command list that ends in continue works like a print() statement that you add from inside the debugger, without editing the source or restarting.
The syntax
commands [bpnumber]bpnumberis the number pdb printed when you created the breakpoint, or the number in theblisting.- If you omit the number, the commands attach to the most recently created breakpoint.
- After you type
commands, the prompt changes from(Pdb)to(com). Every line you type is stored, not run. - You finish the list with
end.
Two special rules apply to the list:
- If the first line is
silent, pdb suppresses the usual announcement when the breakpoint is hit. That announcement is the> file(line)function()line and the source line. Withoutsilent, your output is mixed with that noise on every hit. - A command that resumes execution ends the list. Those commands are
continue,step,next,return,jump,quit, and their abbreviations. Anything typed after one is ignored, so put it last.
A worked example
Save this as discount.py:
def apply_discount(price, rate):
discounted = price * (1 - rate)
return round(discounted, 2)
def total(prices, rate):
result = 0
for price in prices:
result += apply_discount(price, rate)
return result
print(total([10.0, 20.0, 30.0], 0.1))Line 3 is the return in apply_discount. You want to see the input and the discounted price on every call without stopping. Start the program under pdb:
python -m pdb discount.pyThen set the breakpoint and attach the commands:
> /home/you/discount.py(1)<module>()
-> def apply_discount(price, rate):
(Pdb) b 3
Breakpoint 1 at /home/you/discount.py:3
(Pdb) commands 1
(com) silent
(com) p price, discounted
(com) continue
(com) end
(Pdb) c
(10.0, 9.0)
(20.0, 18.0)
(30.0, 27.0)
54.0
The program finished and will be restartedThe program ran to the end without stopping. For each call you got one line with the values. The 54.0 line is the program's own output.
Each line of the list has a job:
silentkeeps the breakpoint quiet.p price, discountedprints both values as a tuple.continueresumes execution.
Without continue, pdb would run the p and then show a (Pdb) prompt, and you would be stopped again.
What happens on each hit
The order of the steps matters when you combine commands with conditions and ignore counts.
If the condition is false, the breakpoint does not count as a hit and the commands do not run. So a conditional breakpoint with a command list only prints for the cases you care about.
Combining commands with conditions
Suppose only prices above 15 matter. Create the breakpoint with a condition, then attach commands to it:
(Pdb) b 3, price > 15
Breakpoint 1 at /home/you/discount.py:3
(Pdb) commands
(com) silent
(com) p price, discounted
(com) continue
(com) end
(Pdb) c
(20.0, 18.0)
(30.0, 27.0)
54.0Here commands has no number, so it attaches to breakpoint 1, which is the last one created. The first call with a price of 10.0 fails the condition and is skipped.
Useful things to put in a list
Any line you can type at the (Pdb) prompt can go in a list. That includes Python expressions and statements. Lines that do not match a pdb command run as Python code.
| Line in the list | What it does |
|---|---|
| `p expr` | Prints one value. |
| `pp locals()` | Pretty-prints all local variables. |
| `w` | Prints the call stack, to show who called this line. |
| `!print(f"price={price}")` | Runs your own formatted message. The `!` makes pdb treat the line as Python even if the first word matches a command name. |
| `bt` | Same as `w`. |
| `continue` | Resumes, and ends the list. |
Printing w on every hit is a cheap way to find out which of several callers produces a bad value.
Removing or replacing commands
- To replace the list, run
commands Nagain and type a new list. The old one is discarded. - To remove the list, run
commands Nand typeendstraight away. - Commands belong to the breakpoint. If you clear the breakpoint with
cl N, its commands go with it. disable Nkeeps the commands but stops the breakpoint from firing.enable Nbrings both back.
Gotchas and edge cases
breakpoint() calls have no number. A call to breakpoint() in your source stops the program, but pdb does not register it as a numbered breakpoint. You cannot attach commands to it. To use commands, set the breakpoint at the prompt with b file:line or b function. A common pattern is to stop once with breakpoint(), then set a numbered breakpoint a few lines later.
Commands vanish with the session. The lists live only in the running debugger. If the program exits and you start a new python -m pdb process, you must type them again. Note that after a program finishes under python -m pdb, pdb restarts it and keeps your breakpoints and commands. A .pdbrc file, covered in a later chapter, is the way to save them across processes.
A resuming command ends the list. If you write next in the middle of a list, pdb treats the list as ending there. Lines after it never run. The same applies to step, return, jump, and quit.
Output is interleaved. The debugger prints to standard output, and so does your program. If your script also prints a lot, the two streams mix. Prefix your own debug output, such as !print("DBG", price), so it is easy to search for.
Tracing makes loops slower. pdb uses Python's trace hook. A breakpoint hit hundreds of thousands of times, even with silent and continue, can slow the program a lot. For hot loops, add a condition to cut the hits, or use an ignore count.
Choosing between commands and a print statement
Commands are not always better than editing the code. Use this to decide.
- Use commands when the code is slow to restart, when you do not want to touch the source, or when you are already in a debugger session and want to watch a value across many hits.
- Use a
print()orloggingcall when you need the output to persist, to be shared, or to run outside pdb. A command list is lost when the session ends. - Use a conditional breakpoint without commands when you want to stop and explore at one particular case, not log many.
Exercises
Exercise
A breakpoint has the list silent, continue, p x, end. You hit the breakpoint but x is never printed. Why, and how do you fix it?
Show answer
continue resumes execution and ends the command list, so p x is ignored. Reorder the list so p x comes before continue: silent, p x, continue, end.
Exercise
Using discount.py from this chapter, write the pdb session that prints only discounted for calls where rate is below 0.5, and never stops at the breakpoint. Which breakpoint line and which commands do you use?
Show answer
Set the conditional breakpoint with b 3, rate < 0.5. Then type commands, followed by silent, p discounted, continue, and end. Run with c. Since rate is 0.1 in the example, every call matches and prints.
Exercise
Your script calls breakpoint() on line 20. You type commands 1 at the prompt and get an error saying the breakpoint number is invalid. What is the cause, and what is a workaround?
Show answer
A breakpoint() call is not registered as a numbered breakpoint, so there is no breakpoint 1 to attach commands to. Create a real breakpoint with b file:line (or b function_name) at the prompt, then attach commands to the number pdb prints.