Sub topic 13
A hypothesis-driven debugging workflow
This chapter assumes you can run Python scripts from a terminal, read a traceback, and use the basic pdb commands (n, s, c, p, w, b). It also assumes you know how to set an environment variable. Here you will combine those commands into a repeatable method.
Why a workflow matters
Beginners often open the debugger and step through every line. That is slow, and it hides the bug in a pile of irrelevant detail. A better habit is to treat the debugger as an experiment tool. You form a guess about the cause, decide what you would see if the guess were true, and then check that one thing.
The method has six steps:
- Reproduce the failure reliably.
- State the symptom precisely, with actual and expected values.
- List hypotheses about the cause.
- For each hypothesis, predict what you will observe at a specific point.
- Use pdb to observe that point and compare it with the prediction.
- Fix the cause, then verify and clean up.
A worked example
Save this as cart.py. It applies percentage discounts to prices and sums the result.
def apply_discounts(prices, rules):
result = {}
for name, price in prices.items():
rate = rules.get(name, 0)
result[name] = price * (1 - rate)
return result
def total(prices):
return sum(prices.values())
prices = {"pen": 2.0, "book": 10.0, "bag": 20.0}
rules = {"book": 10, "bag": 50}
print(total(apply_discounts(prices, rules)))Step 1 and 2: reproduce and state the symptom
Run it:
python cart.pyThe output is -1068.0. The expected total is 21.0, because the pen costs 2.0, the book costs 9.0 after 10% off, and the bag costs 10.0 after 50% off. A total can never be negative here, so some individual price must be negative.
Writing the symptom as "actual -1068.0, expected 21.0" is useful. It tells you the error is large and has the wrong sign, which rules out small rounding problems.
Step 3: list hypotheses
Write down candidates before touching the debugger. Rank them by how cheap they are to test.
| Hypothesis | What you would see if true | Cheapest pdb check |
|---|---|---|
| H1: `total` sums the wrong thing | The dict passed to `total` looks fine, but the sum is wrong | `p prices` inside `total`, then `p sum(prices.values())` |
| H2: input prices are wrong | A negative or odd price in the input dict | `p prices` at the start of `apply_discounts` |
| H3: a discount rate is wrong | A `rate` outside 0 to 1 for some item | Breakpoint on the line that uses `rate` |
Step 4 and 5: predict, then observe
Start with the hypothesis that is cheapest and most likely. Here that is H3. If H3 is true, then at the line result[name] = price * (1 - rate), at least one rate will be greater than 1.
Do not step through the loop three times by hand. Use a conditional breakpoint that only stops when the prediction comes true. Run the script under pdb:
python -m pdb cart.pyThen enter these commands:
(Pdb) b 5, rate > 1
Breakpoint 1 at /home/you/cart.py:5
(Pdb) c
> /home/you/cart.py(5)apply_discounts()
-> result[name] = price * (1 - rate)
(Pdb) p name, price, rate
('book', 10.0, 10)The breakpoint did not fire for pen, because its rate was 0. It fired for book, with a rate of 10. The prediction held, so H3 is supported.
Support is not yet the same as the full cause. A rate of 10 could come from a bad config, or from a unit mismatch. Make the next prediction specific: if the caller passes percentages and the function expects fractions, then rules will contain whole numbers like 10 and 50 everywhere. Check where the value came from by moving up the stack:
(Pdb) w
/home/you/cart.py(15)<module>()
-> print(total(apply_discounts(prices, rules)))
> /home/you/cart.py(5)apply_discounts()
-> result[name] = price * (1 - rate)
(Pdb) u
> /home/you/cart.py(15)<module>()
-> print(total(apply_discounts(prices, rules)))
(Pdb) p rules
{'book': 10, 'bag': 50}Both values are whole percentages. The cause is a unit mismatch: the data uses percent, and the function treats the number as a fraction. Everything you saw fits this explanation, and you rejected nothing by guessing.
Step 6: fix and verify
Change the calculation so the function converts percent to a fraction:
def apply_discounts(prices, rules):
result = {}
for name, price in prices.items():
rate = rules.get(name, 0) / 100
result[name] = price * (1 - rate)
return resultRe-run the script. It now prints 21.0, which matches the expected value from step 2. That comparison against a number you wrote down earlier is your verification. Without it, "the output looks plausible" is a weak check.
Getting more from each pass
Make observation cheap
Stopping at every iteration costs attention. Two techniques reduce it:
- A conditional breakpoint stops only when your hypothesis predicts something unusual. Use
b file.py:line, condition. - Breakpoint commands print values and continue, so you can collect evidence from many iterations in one run.
(Pdb) b 5
(Pdb) commands 1
(com) silent
(com) p name, rate
(com) continue
(com) end
(Pdb) c
('pen', 0)
('book', 10)
('bag', 50)This prints one line per loop pass and never stops. Reading the whole sequence at once often shows the pattern faster than stepping.
Test one change at a time
You can also test a hypothesis by changing state. At the prompt, !rate = rate / 100 followed by n and p result shows whether the fix would produce the right value, without editing the file. Use this to confirm a fix, then make the edit in the source. A change made only inside pdb is lost when the session ends.
Record what you ruled out
When a hypothesis is rejected, note it, even briefly. In a long session it is easy to re-test the same idea. A short list in a scratch file, with "rejected: H2, prices looked correct at line 1", is enough.
Common mistakes
- Stepping without a question. If you cannot say what you expect to see, you are browsing, not testing. Stop and write the hypothesis first.
- Stopping too late. A breakpoint placed after the bad value was computed shows only the result. Place it before the suspect line, or step backward through the call stack with
u. - Trusting your reading of the code. The point of the debugger is to see actual values. If
p xdisagrees with what you believed, believe the debugger. - Changing several things at once. If you edit two lines and the bug disappears, you do not know which one mattered.
- Leaving debugging code behind. A forgotten
breakpoint()will hang a script that runs unattended.
Choosing the right entry point
The way you start pdb should follow from the hypothesis.
| Situation | Best entry point |
|---|---|
| You know roughly where the bug is | `breakpoint()` on the line before it |
| You have no idea where it is | `python -m pdb script.py`, then set breakpoints with `b` |
| The program crashes with an exception | `pdb.post_mortem()` or `python -m pdb script.py`, which enters post-mortem on an uncaught exception |
| A test fails | `pytest --pdb`, which opens pdb at the failing assertion |
For a crash, the traceback already names the failing line. Your first hypothesis is usually about the values in that frame. Post-mortem mode lets you test it with p, and u and d let you inspect the callers that supplied bad arguments.
When your hypotheses all fail
If every hypothesis is rejected, your mental model of the program is wrong somewhere. Go back one level:
- Confirm the symptom again. Is the program actually running the file you are editing?
- Check the earliest point where the data is still correct, then move forward until it is wrong. This is a manual bisection: pick the midpoint, observe, and discard half the code.
- Print the types as well as the values with
p type(x). A string"10"and an integer10look similar in some output but behave differently.
Bisection works because the bug lives between the last place the state was correct and the first place it is wrong. Each observation halves that gap.
Exercise
A function average(scores) returns 0.0 for a list that should average 82.5. You suspect that scores is empty by the time it reaches the function, or that the sum is computed incorrectly. Write two hypotheses, state what you would predict under each, and give the pdb commands you would use to test them.
Show answer
Hypothesis 1: scores is empty or truncated when it arrives. Prediction: p scores at the top of the function shows [] or fewer items than expected. Hypothesis 2: the sum or division is wrong. Prediction: scores looks correct, but p sum(scores) or p len(scores) gives an unexpected number. Commands: put breakpoint() as the first line of average, run the script, then enter p scores, p len(scores), p sum(scores). If scores is wrong, use w and u to move to the caller and find where the list was built. If it is correct, step with n through the calculation and p each intermediate value.
Exercise
In the cart.py example, which single command would stop the program only for items whose rate is outside the range 0 to 1, and why is that better than stepping with n?
Show answer
b 5, rate > 1 or rate < 0 sets a conditional breakpoint on line 5. It stops only when the hypothesis (a bad rate) is true, so you skip the iterations that behave normally and go directly to the evidence.