Sub topic 10
Controlling breakpoint() with PYTHONBREAKPOINT
This chapter assumes you can start a pdb session with breakpoint(), read a traceback, and set an environment variable in your shell. It covers how breakpoint() decides what to run, what values PYTHONBREAKPOINT accepts, and the mistakes that most often surprise people.
What breakpoint() actually does
breakpoint() does not start pdb directly. It calls sys.breakpointhook(), and that function chooses what to run. The default hook reads the PYTHONBREAKPOINT environment variable and acts on it.
This indirection gives you two controls without editing source code:
- You can switch every
breakpoint()call in a program on or off. - You can send those calls to a different debugger or to your own function.
The environment variable is read each time breakpoint() is called. It is not read once at startup. Code that changes os.environ["PYTHONBREAKPOINT"] while running affects later calls.
The accepted values
| Value | Effect |
|---|---|
| unset, or set to an empty string | Calls `pdb.set_trace()`. |
| `0` | `breakpoint()` returns immediately and does nothing. |
| `pdb.set_trace` | Same as the default, written out. |
| `ipdb.set_trace` | Imports `ipdb` and calls its `set_trace`. |
| `package.module.function` | Imports `package.module` and calls `function`. |
| `print` | A name without a dot is looked up in `builtins`, so this calls `print`. |
The rule is simple. The value is split at its last dot. The left part is a module to import, and the right part is the attribute to call. With no dot, the module is builtins.
Disabling breakpoints without editing code
Setting the value to 0 turns every breakpoint() call into a no-op. This is useful when you have left a call in code that now runs in a script, a test run, or a deployment where nobody can type at a prompt.
PYTHONBREAKPOINT=0 python script.pyThe same line works for temporarily running the whole program without pauses so you can check whether the bug still appears. On Windows cmd, use set PYTHONBREAKPOINT=0 on its own line first. In PowerShell, use $env:PYTHONBREAKPOINT = "0".
Disabling is a stopgap. A breakpoint() call committed to a shared branch will still stop anyone who runs the code without the variable set. Remove calls before you commit, and consider a pre-commit check that searches for them.
Choosing a different debugger
Any third-party debugger that offers a set_trace-style function can be used. For example, with ipdb installed:
pip install ipdb
PYTHONBREAKPOINT=ipdb.set_trace python script.pyYour source stays the same. Every breakpoint() now opens ipdb instead of pdb. To make this the default in your shell session, export the variable:
export PYTHONBREAKPOINT=ipdb.set_tracePut that line in your shell profile only if you want it for every Python program you run. Be aware that it also applies to programs you did not write, and to tools such as test runners that you launch from that shell.
Writing your own hook
The target can be any importable callable. That lets you build behavior that pdb does not offer. The next example defines a hook that logs where it was called and lists the local variable names, then lets the program continue.
Create loghook.py:
import inspect
def hook(*args, **kwargs):
caller = inspect.currentframe().f_back
where = f"{caller.f_code.co_filename}:{caller.f_lineno}"
names = sorted(caller.f_locals)
print(f"[breakpoint] {where} args={args} locals={names}")Create app.py in the same directory:
def total(prices):
result = 0
for price in prices:
result += price
breakpoint("after add")
return result
print(total([3, 4]))Run it with the hook selected:
PYTHONBREAKPOINT=loghook.hook python app.pyThe output has one line per loop iteration, then the result:
[breakpoint] app.py:5 args=('after add',) locals=['price', 'prices', 'result']
[breakpoint] app.py:5 args=('after add',) locals=['price', 'prices', 'result']
7Two details matter here:
loghookis found because Python puts the script's directory onsys.path. If your hook lives elsewhere, it must be importable from where you run the command.inspect.currentframe().f_backis the frame that calledbreakpoint(). The built-in is written in C and has no Python frame of its own, so the hook's caller is your code.
You can use the same technique to count how often a line runs, write values to a file, or trigger a debugger only when a condition holds.
Arguments are passed through
Whatever you pass to breakpoint() is forwarded to the hook unchanged. With PYTHONBREAKPOINT=print, the call breakpoint("here") prints here. This is a quick way to turn breakpoints into trace output.
The default hook, pdb.set_trace, accepts only a keyword-only header argument. Passing a positional argument to breakpoint() while the default is active raises TypeError. So breakpoint("after add") works with loghook.hook and with print, but fails with plain pdb. The safest habit is to call breakpoint() with no arguments unless you control the hook.
Replacing the hook inside Python
The environment variable is only the default hook's configuration. You can replace the hook itself by assigning to sys.breakpointhook:
import sys
def quiet_hook(*args, **kwargs):
print("breakpoint ignored")
sys.breakpointhook = quiet_hook
breakpoint()When you replace sys.breakpointhook, PYTHONBREAKPOINT is no longer consulted, because the code that reads it lived in the original hook. The original is saved as sys.__breakpointhook__, so you can restore it:
import sys
sys.breakpointhook = sys.__breakpointhook__This is how test frameworks and IDEs capture breakpoint() calls. A tool that installs its own hook can quietly override the variable you set, which is worth remembering when PYTHONBREAKPOINT seems to have no effect.
Failure modes and gotchas
A bad value is a warning, not an error
If the module cannot be imported or the attribute does not exist, Python emits a RuntimeWarning and breakpoint() returns without pausing. For example, with PYTHONBREAKPOINT=ipdb.set_trace and no ipdb installed, you see a message like this:
RuntimeWarning: Ignoring unimportable $PYTHONBREAKPOINT: "ipdb.set_trace"The program then runs straight past every breakpoint. If your program seems to ignore breakpoint(), check the warning output first. Warnings can be hidden by -W ignore or by logging configuration.
Typos in the module path
PYTHONBREAKPOINT=pdb.settrace fails the same way, since there is no such function. The value is case-sensitive.
Interpreter flags that skip the variable
Running with python -E or python -I makes Python ignore all PYTHON* environment variables. Under those flags the default pdb.set_trace runs no matter what you set. If you use -I in a launcher script, the variable has no effect.
Output being captured
A debugger needs a terminal to read from. If a framework redirects standard input or output, as pytest does by default, the (Pdb) prompt may not appear properly. The pytest chapter in this tutorial covers -s and --pdb.
Subprocesses inherit the variable
An exported PYTHONBREAKPOINT is passed to every child process. A program that launches workers will have each worker honor it, and several workers may try to open prompts on the same terminal. Setting PYTHONBREAKPOINT=0 for the whole tree is often the right choice for automated runs.
Choosing an approach
| Goal | Approach |
|---|---|
| Run without any pauses | `PYTHONBREAKPOINT=0` |
| Use a different debugger for one run | Set the variable on the command line only |
| Use a different debugger always | Export it in your shell profile |
| Log or count instead of stopping | Write a hook and point the variable at it |
| Intercept in a test harness or tool | Assign `sys.breakpointhook` |
Prefer setting the variable on the command line for a single run, as in PYTHONBREAKPOINT=0 python app.py. It leaves no lasting state, so you cannot forget about it later.
Exercise
You run PYTHONBREAKPOINT=mytools.dbg python app.py. The program finishes without ever stopping, and you see RuntimeWarning: Ignoring unimportable $PYTHONBREAKPOINT: "mytools.dbg". Give two likely causes and what the program did at each breakpoint() call.
Show answer
Either the module mytools cannot be imported (it is not installed, or its directory is not on sys.path), or mytools imports but has no attribute named dbg. In both cases the default hook issues the warning and returns, so each breakpoint() call did nothing and the program ran to the end.
Exercise
What does breakpoint("checkpoint") do when PYTHONBREAKPOINT is unset, and what does it do when PYTHONBREAKPOINT=print?
Show answer
With the variable unset, the hook is pdb.set_trace, which accepts only a keyword-only header argument, so the positional string raises TypeError. With PYTHONBREAKPOINT=print, the name has no dot so it resolves to builtins.print, and the call prints checkpoint without pausing.
Exercise
A teammate replaced sys.breakpointhook in a test setup file. You now set PYTHONBREAKPOINT=ipdb.set_trace and nothing changes. Why, and how can you restore the default behavior in code?
Show answer
The environment variable is read only by the original hook, so once sys.breakpointhook is replaced, the variable is never consulted. Assign sys.breakpointhook = sys.__breakpointhook__ to restore the original hook, which then honors PYTHONBREAKPOINT again.