Sub topic 1
Pausing your program with breakpoint()
Prerequisites
Assume you can run Python scripts from a terminal, read a traceback, and use functions, loops, and exceptions. You should also know how to set an environment variable.
Pausing your program with breakpoint()
Python's breakpoint() built-in pauses execution and opens the standard-library debugger, pdb. The debugger gives you a prompt where you can inspect values and control execution.
def mean(values):
total = sum(values)
breakpoint()
return total / len(values)
print(mean([2, 4]))Run this program normally. Python stops at breakpoint() and displays a (Pdb) prompt. The current line has not run yet.
> Note > Remove debugging breakpoints before committing code, or control them with the PYTHONBREAKPOINT environment variable.
Starting a script under python -m pdb
You can start debugging before the first line runs. Give the script path to pdb as a Python module:
python -m pdb script.pyExecution pauses at the first executable line. This approach is useful when the bug occurs before a convenient breakpoint() call, such as during setup or argument parsing.
Reading the (Pdb) prompt and getting help
At (Pdb), type a debugger command and press Enter. Use help for a command list or help command for details.
| Command | Purpose |
|---|---|
| `p expression` | Evaluate and print an expression |
| `pp expression` | Pretty-print a value |
| `l` | List nearby source lines |
| `a` | Show the current function's arguments |
| `h command` | Show help for a command |
For example, p values displays the local variable named values. If an expression has the same name as a debugger command, prefix it with !, such as !print.
Stepping through code: next, step, continue, return, until
Use these commands to control how execution advances:
n(next) runs the current line and stops at the next line in the same frame.s(step) runs the current line and enters a called function.c(continue) runs until the next breakpoint or program exit.r(return) runs until the current function returns.until lineruns until execution reaches a later line in the current frame.
A common workflow is to use n to follow normal code, s when a function call looks suspicious, and c after checking the important state.
Exercise
Which command should you use to enter a function called by the current line?
Show answer
Use s, or step; n runs the call without entering it.