Sub topic 6
Check the Diagnosis Against the Evidence
What this chapter assumes
You can read a Python traceback, run a script from a terminal, and use git. You have already written a debugging prompt that includes the code, the full error, the environment, and the expected behavior. This chapter covers the next step. The assistant has replied with an explanation, and you must decide whether to believe it before you change anything.
A diagnosis is a hypothesis
An assistant produces the most plausible explanation for the text you gave it. It usually can't run your program, so it can't observe your program. Its answer is a hypothesis in the same way a colleague's guess over your shoulder is a hypothesis. It may be right, and it is often well written, but fluent wording is not evidence.
Your job is to compare the claims in the answer with three sources of evidence you control:
- The traceback: the error type, the message, and the frames.
- The code: what the failing line actually does.
- The runtime state: the values that exist when the failure happens.
If a claim agrees with all three, accept it. If it conflicts with any of them, or says something none of them can confirm, treat it as unproven.
Break the answer into claims
A typical reply bundles several statements. Separate them and check each one. Here is the failing function from earlier in the tutorial:
def average(values):
return sum(values) / len(values)
print(average([]))And the traceback:
Traceback (most recent call last):
File "stats.py", line 5, in <module>
print(average([]))
File "stats.py", line 2, in average
return sum(values) / len(values)
ZeroDivisionError: division by zeroSuppose the assistant replies: "The error happens because values is empty, so len(values) is 0 and the division fails. sum([]) is fine and returns 0. Add a check before dividing."
That contains four claims. The table shows where each one can be checked.
| Claim | Where to check it | Result |
|---|---|---|
| The error is a division by zero | Last line of the traceback | Confirmed: `ZeroDivisionError: division by zero` |
| The failing line is the division in `average` | Innermost frame, `stats.py`, line 2 | Confirmed |
| `values` is empty at that moment | Runtime state | Not yet observed |
| `sum([])` returns 0 without error | Python itself | Check in a REPL: `sum([])` is `0` |
The first two checks only require reading what you already have. The third is the one that matters, and it's the one the traceback can't prove. The traceback says a division by zero happened. It does not say why the divisor was zero.
Test a prediction
A good check starts with a prediction: if the diagnosis is correct, this specific thing must be true. Then you look for it. Here the prediction is that values is [] and len(values) is 0 when line 2 runs. A temporary probe confirms or refutes it:
def average(values):
print("DEBUG values =", repr(values), "len =", len(values))
return sum(values) / len(values)
print(average([]))The output begins with DEBUG values = [] len = 0, and the traceback follows. The prediction held, so the diagnosis is supported by an observation you made yourself. Remove the probe afterwards so it doesn't end up in your commit.
A prediction can fail, and a failure is useful. If the probe had printed values = [1, 2, 3], the assistant's explanation would be wrong however confident it sounded, and you would have learned that before editing any code.
Good probes are cheap and tell you something definite:
- A
printorreprof the suspect value just before the failing line. - A REPL call such as
sum([])that tests a claim about library behavior. - A debugger breakpoint at the failing frame, inspecting the local variables.
python -cwith one expression, for checking a claim about the language.
Separate the symptom from the cause
The failing line shows where the program stopped. It does not always show where the mistake was made. Here, the division is the symptom. The cause could be one of two different things:
averageis public and should reject empty input with a clear error.averageis correct for its callers, and some caller is wrongly passing an empty list.
These lead to different fixes. Consider a caller:
def average(values):
return sum(values) / len(values)
def passing_scores(rows):
return [r["score"] for r in rows if r["score"] >= 50]
rows = [{"score": 30}, {"score": 45}]
print(average(passing_scores(rows)))This also ends in ZeroDivisionError. An assistant that sees only average will say to add a guard. That is true for the function, but the traceback has an extra frame for passing_scores' caller, and the real question is a product decision: what should a report show when nobody passed? A guard that raises ValueError might crash a report page that should say "no passing scores". A guard that returns 0 would show a misleading average.
Ask whether the diagnosis explains why the bad value arrived, not only why the line failed. A complete diagnosis names the origin of the value.
Ask for the reasoning, then check it
The prompt template from the previous chapter asks for reasoning from the traceback before a fix. That pays off here, because reasoning can be audited and a bare answer can't. When the explanation cites a line number, find that line. When it quotes a message, find that message in your output. A cited detail that doesn't exist in your files or logs is a strong sign the assistant is guessing.
You can also push on the answer directly with follow-up questions:
- "Which line of the traceback supports that?"
- "What would I see if your diagnosis were wrong?"
- "Give two other explanations for this error and say how to tell them apart."
- "What does this code assume about its input, and where is that assumption set?"
The second and third questions are the most useful. They turn one story into competing hypotheses, and each hypothesis comes with a test you can run.
Weigh competing explanations
Sometimes the evidence fits more than one explanation. For the average case, "caller passes an empty list" and "function lacks input validation" are both consistent with the traceback. Pick the test that separates them. Log or print the argument at the call site and see whether empty input is expected behavior or a data bug.
When you can't separate two hypotheses with the evidence you have, say so, and collect more. Don't choose the one that sounds better. The next chapters on iteration cover how to send new evidence back.
Warning signs in an answer
Some features of a reply should lower your trust until you've checked it. This chapter only flags them. The following chapter covers the common failure patterns in more detail.
- It names a function, flag, or module you can't find in the documentation or your installed version.
- It doesn't mention the error type or the frame from your traceback.
- It says "this is probably fine" about the line that actually failed.
- It proposes catching the exception or returning a default without explaining why the bad input happens.
- It changes several unrelated things at once.
Decide: accept, probe, or reject
After checking the claims, you will be in one of three positions.
- Accept. Every claim matches the traceback and the code, and you have observed the key runtime value. Move on to a small fix.
- Probe. The explanation is plausible but unobserved. Run the cheapest probe that tests it, then decide again.
- Reject. A claim conflicts with the evidence. Send the contradicting detail back with the exact output, for example: "The probe shows
values = [1, 2, 3], so it isn't empty. Where else could the zero come from?"
For the average([]) case, the probe confirmed the empty list, so you accept the diagnosis. The smallest change that follows from it rejects empty input explicitly:
def average(values):
if not values:
raise ValueError("average() requires at least one value")
return sum(values) / len(values)Whether that exact fix is right depends on the second question above, who calls average and what they expect. The next chapters cover applying and verifying a fix.
Exercise
An assistant says your KeyError: 'email' is caused by a missing .get() call on line 12. The traceback points to line 31 of a different file, and the assistant's reply does not mention that line. List two checks you would make, and say what you would do if the first check contradicts the answer.
Show answer
First, compare the claim with the evidence: open the file and line named in the innermost frame (line 31) and confirm whether line 12 is even involved. Second, test the prediction with a probe, such as printing repr(record) and record.keys() just before line 31, to see whether 'email' is really absent and where the record comes from. If the first check contradicts the answer (the failing line is somewhere else), reject the diagnosis, and send the assistant the exact traceback and probe output, asking it to explain the failure at line 31 and where the record is built.
Exercise
A caller passes passing_scores(rows) into average, and the result is an empty list. The assistant suggests a guard in average that returns 0. Why might this be a symptom-level fix, and what question would you ask before accepting it?
Show answer
Returning 0 hides the failure and reports a misleading average for a case with no data. It treats the division as the problem when the empty input may be the real issue. Before accepting it, ask what the caller should show when nobody passes, and whether an empty list is valid input or a data bug upstream. Then choose between raising an error, returning a marked "no data" value, or fixing the caller.