Debugging and reading code¶
What you'll be able to do¶
- Turn a surprising result into a repeatable failure and a testable explanation.
- Read a Python traceback, choose a useful debugging tool, and narrow the search for a bug.
- Trace data through unfamiliar code and report a bug so someone else can reproduce it.
Make the failure repeatable¶
Debugging is a small scientific experiment. Observe the failure, hypothesize a cause, predict what that cause implies, test one prediction, then narrow the search. Keep the failing input and the exact command. A bug that happens only “sometimes” needs a record of what sometimes means: time, input order, random seed, environment, or concurrent activity.
Suppose a function should produce every width-three window from four values. You expect two windows, but see one. Write the smallest failing case before changing code:
values = [10, 20, 30, 40]
expected = [(10, 20, 30), (20, 30, 40)]
actual = [tuple(values[i:i + 3]) for i in range(len(values) - 3)]
assert actual == expected, (actual, expected)
The hypothesis is that the loop stops one position too early. It predicts that three values produce zero windows, though they should produce one. Test that prediction. The minimal reproduction removes files, APIs, and other code that cannot explain the failure. It is often half the fix because it identifies the boundary you must inspect.
Write a short debug log: “Hypothesis: the final starting index is excluded. Experiment: use exactly three items. Result: zero windows.” If the prediction fails, revise the hypothesis instead of defending it. Change one thing at a time so the next result has a clear meaning.
Read the traceback from the failure outward¶
Python tracebacks show a stack of function calls. Start at the bottom: read the exception type (ValueError, TypeError, and so on), then its message. Move upward to find the lowest frame in your code. A library frame can be where an error surfaced; the call from your code often explains which input reached it.
def parse_count(text):
return int(text)
def total(texts):
return sum(parse_count(text) for text in texts)
total(["2", "many"])
This raises ValueError while converting "many". The lowest frame points to int(text); the caller shows how that value arrived. Inspect text, then ask whether the caller should validate it or the conversion should reject it. Avoid except: pass: it turns a visible failure into a plausible but wrong answer.
When code raises a clearer error while preserving the cause, it can use raise ... from ...:
try:
count = int("many")
except ValueError as exc:
raise ValueError("invalid count in input row") from exc
The resulting traceback has two exceptions. Read the final exception for the operation's meaning, then the earlier one for the original cause. If you wrap an error, include useful context such as the field or row; never hide the cause just to shorten the output.
Use the cheapest useful tool¶
Start with a small print when you need one value in a local run. Check that execution actually reached that line. For repeated runs or code shared with others, use logging: levels, timestamps, and contextual fields make messages easier to filter and correlate. A log at the wrong path is still no evidence; place it where the disputed value is produced or consumed.
Use assert to test an assumption during development: assert len(batch) > 0, for example. An assertion gives you a nearby failure instead of a bad value that propagates. Do not rely on assertions for required input validation: Python can disable them in optimized runs.
When values change across several calls, stop execution with breakpoint() and inspect state. In Python's pdb, n executes the current line and stops at the next one in this frame (a call on that line runs to completion), s steps into a call, c continues, p expression prints a value, l lists nearby source, where shows the stack, and q quits. python -m pdb script.py starts a script under the debugger and can enter post-mortem debugging after an uncaught exception. In an interactive Python session after an exception, import pdb; pdb.pm() inspects the last traceback. An IDE debugger offers the same basic ideas with a visual interface.
Cut the search space in half¶
If the bug appeared during a series of commits, use git bisect to find the first bad commit. From a bad checkout, run:
At each checkout, run the same reliable reproducer and mark that commit good or bad. When finished, run git bisect reset. For 32 candidate commits, splitting in half takes about five decisions (32 → 16 → 8 → 4 → 2 → 1), rather than inspecting all 32. A flaky test ruins those decisions, so stabilize it first.
The same halving idea (sometimes called the wolf fence) works inside one function. At a stage where you know the expected intermediate value, compare it with the actual one: if they differ, search upstream; otherwise, search downstream. Temporarily disable half a computation only when doing so preserves a meaningful test. You can also shrink the input: remove half the rows, columns, or request fields, rerun, and retain the half that still fails. Each experiment should answer one question.
Recognize bug signatures without guessing¶
These patterns suggest useful first experiments, not automatic diagnoses:
| Symptom | First check |
|---|---|
| Missing first or last item | Loop bounds and inclusive versus exclusive endpoints |
| Wrong value spreads through later steps | The first None or non-finite value; inspect where it entered |
| One call changes a later call's result | Shared mutable objects, aliases, or mutable default arguments |
| Date or text works on one machine only | Timezone assumptions or text encoding at the boundary |
| Failure disappears when watched | Timing, shared state, and concurrent ordering |
| Works locally but fails elsewhere | Dependency versions, environment variables, and input files |
| A decimal comparison barely fails | Floating-point rounding; compare with a suitable tolerance |
A Heisenbug changes when you observe it: a print can alter timing, especially in concurrent code. A flaky failure can depend on time, randomness, iteration order, concurrency, or network responses. Pin what you can: set a seed, freeze or inject the clock, sort inputs when order is not part of the contract, control concurrent work in a test, and replace a remote response with a recorded local fixture. Save the input that failed. Do not declare a race just because a rerun passed.
Read unfamiliar code by following data¶
Start at an entry point and a test for the behavior you care about. For a request, sketch one path: handler → parser → service → storage → response. Follow the disputed value through that path, rather than reading every function in file order. Search for its name with grep (or your editor's search), use go-to-definition for a call, and inspect the callers that supply its arguments. Run one small case under a debugger when a branch or mutation is unclear.
If you remain stuck after a focused attempt, explain the bug to a person or even a rubber duck. Saying each assumption aloud often exposes the missing step. Ask for help with the expected result, actual result including error type, minimal reproduction and command, environment details that matter, and experiments already tried. That gives someone else a starting point instead of a mystery.
For AI engineers¶
For AI engineers
A training script can run to completion while doing the wrong work. Shapes may broadcast successfully, NaN values can spread through a metric, a data leak can make validation look excellent, and a wrong tokenizer can still produce numbers. Put cheap assertions at boundaries: expected shape, dtype, range, and finite values. Print input distributions as well as loss. Fix random seeds to remove one source of variation; control data order and nondeterministic operations when exact reruns matter. Compare with a trivial baseline, and try to overfit one small batch as a smoke test. If that fails, inspect the data and update path before running a larger experiment.
Common mistakes¶
- Changing several things at once, then being unable to tell which change mattered.
- Trusting a print without checking whether execution reached it or whether it shows the failing case.
- Swallowing an exception with
try/except: pass, leaving a plausible wrong result. - Rerunning a flaky failure without saving its input, seed, time, and command.
- Blaming a library before checking the values and assumptions at the call into it.
Check yourself¶
A width-three window function returns zero windows for three items. What hypothesis and second test would narrow the bug?
The loop may exclude the last valid starting index. Try four items and predict whether it returns one window instead of two. If so, inspect the loop bound.
A traceback ends in a library ValueError, with your parser one frame above it. Where do you start?
Read the error type and message at the bottom, then inspect the value your parser passed into the library. The library frame shows where the error surfaced; your frame shows the input you control.
A test passes unless you add a print. Which sources of variation would you pin before using git bisect?
Check timing and concurrency first, then time, randomness, input ordering, and network data. Keep the failing input and make the test repeatable before marking commits good or bad.
A model's validation metric is unexpectedly excellent. Which cheap checks can distinguish a good model from a silent data error?
Check for train/validation overlap, expected shapes and ranges, finite values, input distributions, and performance against a trivial baseline. A successful run alone does not validate the data path.
Lab¶
Fix five deliberately buggy functions in code/debugging/starter/lab.py. They cover a missing sliding window, shared mutable state, a rounded metric, a hidden conversion error, and unstable ordering. For each bug, record a hypothesis, one experiment, and its result using the template in code/debugging/README.md. Run: cd code/debugging && PYTHONPATH=starter python -m pytest tests -q. Done means all five behavior tests pass while preserving each function's stated contract.
Go deeper¶
- Python documentation for tracebacks,
logging, andpdb. - pytest documentation for small, focused reproductions.
- MIT Missing Semester for shell and version-control tools.
- Software Engineering Handbook, chapter 14 "Observability".