Sub topic 8
Conditional breakpoints and ignore counts
A plain breakpoint stops every time execution reaches its line. In a loop that runs 10,000 times, that means pressing c 10,000 times to reach the one iteration that matters. Conditions and ignore counts let you tell pdb which pass you care about.
This chapter assumes you can start a pdb session with breakpoint() or python -m pdb, and that you know the basic b, c, p, and n commands from earlier chapters.
Setting a condition when you create the breakpoint
Add a comma and a Python expression after the location. The breakpoint stops only when the expression is true in the frame that reaches the line.
orders = [{"id": n, "qty": 5} for n in range(1, 11)]
orders[6]["qty"] = -2
def total_cost(order):
price = 3
return order["qty"] * price
def main():
grand = 0
for order in orders:
grand += total_cost(order)
print(grand)
main()The total printed by this script is wrong because order 7 has a negative quantity. Save it as shop.py and run it under pdb:
python -m pdb shop.pyThen set a conditional breakpoint on line 5, the first line of total_cost, and continue:
(Pdb) b 5, order["qty"] < 0
Breakpoint 1 at /home/you/shop.py:5
(Pdb) c
> /home/you/shop.py(5)total_cost()
-> price = 3
(Pdb) p order
{'id': 7, 'qty': -2}pdb reached line 5 ten times. It stopped only once, on the call where the condition was true.
The condition is evaluated with the frame's own globals and locals. That is why order is visible even though it is not a global. You can use any expression: function calls, in tests, string comparisons, or and/or combinations.
(Pdb) b shop.py:11, order["id"] > 3 and order["qty"] == 5
(Pdb) tbreak shop.py:5, order["id"] == 7The second line shows that tbreak accepts a condition too. A temporary breakpoint with a condition is deleted after the first time it actually stops, not after the first time the line is reached.
Adding, changing, and removing a condition later
If you already have a breakpoint, use condition with the breakpoint number:
(Pdb) b 11
Breakpoint 2 at /home/you/shop.py:11
(Pdb) condition 2 order["id"] == 7
(Pdb) condition 2 order["id"] == 9
(Pdb) condition 2
Breakpoint 2 now unconditional.Running condition N expr replaces any earlier condition. Running condition N with no expression removes it. This is usually quicker than clearing a breakpoint and creating a new one, because the breakpoint keeps its number and its hit count.
Run b with no arguments to see what each breakpoint is doing:
(Pdb) b
Num Type Disp Enb Where
1 breakpoint keep yes at /home/you/shop.py:5
stop only if order["qty"] < 0
breakpoint already hit 7 timesTwo details in that listing matter later. The stop only if line shows the active condition. The hit count is 7 even though the breakpoint stopped only once, because pdb counts every time an enabled breakpoint's line is reached, whether or not the condition was true.
Ignore counts
An ignore count tells pdb to skip the next N times the breakpoint would otherwise stop. Use it when you know "the problem happens on the seventh pass" but have no expression that identifies it.
(Pdb) b 11
Breakpoint 1 at /home/you/shop.py:11
(Pdb) ignore 1 6
Will ignore next 6 crossings of breakpoint 1.
(Pdb) c
> /home/you/shop.py(11)main()
-> grand += total_cost(order)
(Pdb) p order["id"]
7Six passes were skipped, so pdb stopped on the seventh. The ignore count is now 0. A breakpoint does not remember the original number, so you must set ignore again if you restart and want the same behavior.
Other forms of the command:
ignore 1with no count sets the count to 0 and printsWill stop next time breakpoint 1 is reached.ignore 1 0does the same.ignore 1 3while a count is already set replaces it. It does not add to it.
b shows an active ignore count as ignore next 6 hits.
How conditions and ignore counts combine
You can use both on one breakpoint. The order of checks is:
- If the breakpoint is disabled, nothing happens and the hit count is not increased.
- The hit count increases by one.
- If there is a condition and it is false, execution continues.
- If the ignore count is above zero, it decreases by one and execution continues.
- Otherwise pdb stops.
So the ignore count only counts passes where the condition was true. With condition 1 order["qty"] == 5 and ignore 1 2, pdb skips the first two orders whose quantity is 5 and stops on the third.
Because the fenced diagram must use the required format, here it is in full:
Using the hit count to measure
The hit count lets you answer "how many times does this line run?" without editing the code. Set an ignore count larger than any plausible number of passes, run the program, and read the count afterward.
(Pdb) b 11
Breakpoint 1 at /home/you/shop.py:11
(Pdb) ignore 1 100000
Will ignore next 100000 crossings of breakpoint 1.
(Pdb) cIf the program finishes normally, pdb reports that it is restarting. If it crashes, you land in post-mortem mode. Either way you can then run b and read breakpoint already hit N times. This is useful when a crash happens "somewhere in the loop" and you want to know which pass it was, so you can set a precise ignore count for the next run.
Common errors and edge cases
A condition that raises an exception stops the program. If pdb cannot evaluate the expression, it stops at the breakpoint rather than silently skipping it. A typo such as ordr["qty"] < 0 gives a NameError, and you stop on every pass. Syntax errors are caught earlier, when you type the command, and pdb prints Invalid condition.
Names are looked up in the frame that reaches the line. A condition on a line inside total_cost can use order and price, but not grand, which is a local of main. A name that exists in some passes but not others (for example, a variable assigned only inside an if) fails the same way.
Conditions run on every pass. An expensive condition, such as one that calls a function that queries a database, slows down each iteration. Keep conditions cheap and free of side effects. A condition that appends to a list or increments a counter changes the program being debugged.
Use == for comparison. b 5, order["qty"] = -2 is a syntax error. Also remember to quote strings inside the condition: b 5, order["name"] == "bolt".
The line must be executable. If you set a breakpoint on a blank line or a comment, pdb refuses with Blank or comment. Choose the next line of real code.
Conditions inside your code versus in pdb
You can get the same effect by writing if order["qty"] < 0: breakpoint() in the source. This approach survives restarts and works in code you launch from tools that do not accept pdb commands. The cost is that you edit and re-save the file, and you must remember to remove the line. The b file:line, condition form touches no source, so it is better for quick investigation. Use the in-source form when the condition is complex enough that you want it in a version-controlled test case.
Command summary
| Command | Effect |
|---|---|
| `b 5, expr` | Create a breakpoint that stops only when `expr` is true |
| `tbreak 5, expr` | Same, but delete it after the first real stop |
| `condition N expr` | Set or replace the condition on breakpoint N |
| `condition N` | Make breakpoint N unconditional |
| `ignore N count` | Skip the next `count` stops of breakpoint N |
| `ignore N` | Reset the ignore count to 0 |
| `b` | List breakpoints, conditions, ignore counts, and hit counts |
Exercise
In shop.py, you run b 11, order["qty"] == 5, then ignore 1 3, then c. At which order id does pdb first stop, and what does the hit count show for breakpoint 1 at that moment? (Orders 1 to 10 each have quantity 5, except order 7, which has quantity -2.)
Show answer
pdb stops on order 4. Orders 1, 2, and 3 satisfy the condition, and each uses up one of the three ignored crossings. Order 4 is the fourth true pass, so it stops there. The hit count is 4, because every pass through line 11 is counted when the breakpoint is enabled, and orders 1 to 4 were the only passes so far.
Exercise
You typed b 5, order["qty"] < 0 but pdb stops on every call to total_cost, and you notice the stop message mentions an error. What is the most likely cause, and how do you fix it without deleting the breakpoint?
Show answer
The condition raises an exception when evaluated, for example because of a misspelled name, so pdb stops instead of skipping the pass. Correct it with condition 1 order["qty"] < 0, using the right name and the breakpoint's number. Run b afterward to confirm the stop only if line.
Exercise
You do not know how many times line 11 runs before a crash. Describe how to find out using only pdb commands.
Show answer
Run b 11, then ignore 1 100000, then c. When the program crashes or ends, run b and read breakpoint already hit N times. N is the number of passes through the line.