Sub topic 3
Automating Breakpoints and Debugging Crashes
Assume you can run Python from a terminal, read tracebacks, and use functions, loops, exceptions, and environment variables. This chapter focuses on making pdb stop only when useful.
Automating breakpoints with commands
A breakpoint can run commands automatically. This is useful when you want to observe a value without pausing every time.
(Pdb) b 8
(Pdb) commands 1
(com) silent
(com) p x
(com) continue
(com) endBreakpoint 1 now prints x and continues. silent prevents the usual stop message. Use b to list breakpoints and cl 1 to clear breakpoint 1.
Controlling `breakpoint()` with `PYTHONBREAKPOINT`
The breakpoint() built-in normally calls pdb.set_trace(). You can change that behavior without editing source code.
PYTHONBREAKPOINT=0 python script.py
PYTHONBREAKPOINT=pdb.set_trace python script.pyThe first command disables every breakpoint() call. The second explicitly selects the standard debugger. This is useful in tests or production-like runs where accidental pauses would be disruptive.
> callout note > Treat breakpoint() as temporary diagnostic code. Disable it in automated runs with PYTHONBREAKPOINT=0, or remove it before committing.
Debugging after a crash with post-mortem mode
Post-mortem debugging opens pdb at the frame where an exception occurred.
import pdb
def load_name(data):
return data["name"]
try:
load_name({})
except Exception:
pdb.post_mortem()At the (Pdb) prompt, use w to inspect the stack and p to evaluate variables.
Saving your setup in `.pdbrc`
A .pdbrc file in your home directory can contain commands that pdb loads at startup. For example:
alias pl p locals()You can then type pl to inspect local variables. Keep aliases short and predictable. A project-specific .pdbrc can also be placed beside the program when the setup should be shared.
A hypothesis-driven workflow
Do not step randomly. Form a hypothesis, inspect evidence, and test the smallest useful assumption.
Debugging failing tests with pytest
Run the failing test under the debugger:
pytest --pdb -s tests/test_names.py--pdb enters post-mortem mode after a failure. -s allows normal output to appear, which helps when the test prints diagnostic information.
Limits and alternatives
pdb is portable and requires no extra package, but its terminal interface is less convenient for large applications or asynchronous code.
| Need | Consider |
|---|---|
| Visual breakpoints and watches | An IDE debugger |
| Rich tracebacks and local inspection | `ipdb` or `pdb++` |
| Production failure history | Logging and error tracking |
Exercise
How can you prevent all calls to breakpoint() from pausing a test run?
Show answer
Run the tests with PYTHONBREAKPOINT=0.