Sub topic 1
Pausing your program with breakpoint()
When a program misbehaves, you often want to stop it at a chosen line and look around. The breakpoint() built-in does this. You add one line to your code, run the program as usual, and execution pauses at that point inside the Python debugger, pdb. This chapter covers what breakpoint() does, where it stops, how it reaches pdb, and the mistakes people make with it.
Prerequisites
This chapter assumes you can:
- Write and run Python scripts from a terminal.
- Use functions, loops, and exceptions.
- Read a traceback and find the line that raised the error.
- Set an environment variable on the command line.
You need Python 3.7 or newer, because breakpoint() was added in 3.7.
What breakpoint() does
breakpoint() is a built-in function, like print() or len(), so it needs no import. When Python executes the call, it stops the program and opens an interactive prompt in your terminal. The program stays frozen until you tell the debugger to continue.
Here is a function with a bug. The call to breakpoint() sits before the line that fails.
def mean(values):
total = sum(values)
breakpoint()
return total / len(values)
print(mean([]))Save this as mean.py and run python mean.py. You will see something like this:
> /home/you/mean.py(4)mean()
-> return total / len(values)
(Pdb)The output has three parts:
- The first line gives the file, the line number in parentheses, and the function name. Here it is line 4 of
mean.py, insidemean(). - The line starting with
->is the source line that is about to run. It has not run yet. (Pdb)is the prompt. The debugger is waiting for a command.
Notice that the pause happens at line 4, not line 3. The debugger stops before the next statement after the breakpoint() call, not on the call itself. Everything above that line has already run. The line shown after -> has not.
A first session
At the prompt, p prints the value of an expression. Try these commands, then c to continue:
(Pdb) p total
0
(Pdb) p values
[]
(Pdb) p len(values)
0
(Pdb) cThe values show the cause. values is empty, so len(values) is 0 and the division fails. After c (short for continue), the program resumes and ends with the usual traceback:
Traceback (most recent call last):
File "/home/you/mean.py", line 6, in <module>
print(mean([]))
File "/home/you/mean.py", line 4, in mean
return total / len(values)
ZeroDivisionError: division by zeroYou can also type any Python expression at the prompt, not only p. This includes calls, comparisons, and slices. Later chapters cover the full command set. For now you need three commands:
| Command | Short form | Effect |
|---|---|---|
| `continue` | `c` | Resume the program until it ends or hits another breakpoint |
| `quit` | `q` | Stop the debugger and terminate the program |
| `help` | `h` | List the available commands |
q does not return you to normal execution. It raises an exception inside the program that ends it. Use c when you want the program to keep going.
How breakpoint() reaches pdb
breakpoint() does not contain any debugger code. It calls a hook function, sys.breakpointhook(), and passes along any arguments you gave it. The default hook does the following:
- It reads the
PYTHONBREAKPOINTenvironment variable. - If the variable is unset or empty, it calls
pdb.set_trace(). - If the variable is
0, it does nothing and returns. - Otherwise it treats the value as a dotted name, imports that module, and calls that function.
Before Python 3.7, the usual way to do this was to write import pdb; pdb.set_trace(). That still works and does the same thing by default. breakpoint() is shorter, needs no import, and lets you or your team swap debuggers or switch breakpoints off without editing the source. The PYTHONBREAKPOINT variable gets its own chapter. The one thing to remember now is that the line below turns every breakpoint() call into a no-op:
PYTHONBREAKPOINT=0 python mean.pyArguments and where you can put the call
Any positional or keyword arguments you pass to breakpoint() go to the hook. With the default hook, that means pdb.set_trace(). On Python 3.7 and later, pdb.set_trace() accepts a header keyword, which pdb prints before the first prompt. This helps when you have several breakpoints and want to know which one fired:
def process(items):
for i, item in enumerate(items):
if item is None:
breakpoint(header=f"None found at index {i}")
print(item)
process(["a", None, "c"])Be careful here: header works only while the hook is the default one. If PYTHONBREAKPOINT points to a different debugger, that debugger decides what arguments it accepts, and an unexpected keyword raises TypeError.
Because breakpoint() is an ordinary function call, you can put it wherever a statement can go:
- Inside an
ifblock, to stop only when a condition holds. This is the simplest conditional breakpoint. - Inside an
exceptblock, to inspect the state when an error is caught. - Inside a loop, but see the warning below.
- At module level, to examine the program before any function runs.
Where the debugger stops: edge cases
Because the pause happens at the next statement, a few situations look surprising.
If breakpoint() is the last statement in a function, there is no next line in that function. The debugger stops at the function's return, and the line shown is the one that makes the call to the function or the return marker, depending on Python version. The local variables are still available at that point.
If you put breakpoint() at the end of a script, the debugger stops near the end of the module. You can still inspect globals.
If the code runs in a thread, only that thread is paused at the prompt. Other threads keep running, and their output can interleave with the debugger prompt. When you debug threaded code, expect messy terminal output.
Common errors
Input is not a terminal. pdb reads commands from standard input. If your program runs with input piped or redirected, or inside a service with no terminal, the prompt gets no commands and may read end-of-file. pdb treats end-of-file as quit, so the program stops. Debug such programs from an interactive terminal, or run them with PYTHONBREAKPOINT=0 when you do not want to stop.
Leaving breakpoint() in committed code. A forgotten call will freeze a script on someone else's machine, or hang a job on a server. Search for leftovers before committing:
grep -rn "breakpoint()" --include="*.py" .Shadowing the built-in. If a module defines its own name breakpoint, for example breakpoint = 5, then breakpoint() raises TypeError and never reaches the debugger. Avoid reusing built-in names.
Expecting the call line to be shown. Remember that the -> line is the next line to run, not the breakpoint() line. When you read the surrounding source, the call itself is the line above.
Using it in a program with a graphical or web front end. The prompt appears in the terminal where the process was started, not in the browser or window. Check that terminal if your app seems frozen.
Summary of the model
breakpoint()callssys.breakpointhook(), which by default callspdb.set_trace().- The program pauses before the next statement and shows a
(Pdb)prompt. cresumes,qends the program,pprints an expression, andhlists commands.PYTHONBREAKPOINT=0silences everybreakpoint()call without code changes.- Remove the calls before you commit.
Exercise
You add breakpoint() on line 10 of a script, and line 11 is result = compute(x). At the (Pdb) prompt, you type p result. What happens, and why?
Show answer
pdb stops before line 11 runs, so result has not been assigned yet. If result was never defined earlier, p result prints a NameError message from the debugger. If it was defined earlier, you see the old value. You need to step past line 11 with n before result holds the new value.
Exercise
A teammate says that running PYTHONBREAKPOINT=0 python app.py "removes" the breakpoint() calls from app.py. Is that accurate? What does it do instead, and what is the risk of relying on it instead of deleting the calls?
Show answer
It is not accurate. The calls stay in the source. The default sys.breakpointhook() reads the variable, sees 0, and returns without opening pdb. The risk is that anyone who runs the script without that variable set will hit the debugger and may hang the program, especially in a job or service with no terminal. Delete leftover calls before committing.