Breakpoints and Interactive Debuggers

Breakpoints pause execution at a specific line or condition so you can inspect stack frames, variables, and step-by-step execution, though timing-sensitive concurrency bugs still require logs.

One-Sentence Definition

A breakpoint pauses program execution at a specified location or when a condition holds, allowing you to inspect stack frames and local variables and step through subsequent execution—though because pausing alters timing, concurrency bugs still require logs and traces.

Why It Matters

  • Far richer context than print debugging: A single pause exposes every local variable and the full call stack without repeatedly inserting print statements and re-running.
  • Built for complex state: If a loop fails only on iteration 1,000, a conditional breakpoint stops execution exclusively on that iteration.
  • Fastest way to understand unfamiliar code: Setting a breakpoint inside framework code and stepping through execution often reveals how it works faster than reading documentation alone.

Boundaries & Caveats

Debugger commands evaluate expressions inside the selected stack frame, and some expressions can mutate program state as a side effect. When remote debugging, always verify that you are attached to the intended target process; interactive features vary across Python versions and terminal environments.

How It Works / Diagram

Since Python 3.7, the built-in breakpoint() function (PEP 553) drops into pdb by default; you can switch debuggers or disable breakpoints globally (by setting PYTHONBREAKPOINT=0) via the PYTHONBREAKPOINT environment variable: https://peps.python.org/pep-0553/ ; pdb command reference: https://docs.python.org/3/library/pdb.html

Figure 1

Quick reference for common pdb commands:

Command Action Command Action
b line[, cond] Set a (conditional) breakpoint n Step to next line (step over calls)
c Continue to next breakpoint s Step into function call
p expr Print expression value r Continue until current function returns
pp Pretty-print value w / where Print call stack trace
l / ll List source code around current line u / d Move up or down stack frames
interact Start an interactive Python shell q Quit debugger

Runnable Example

Script: examples/14_breakpoint.py. Verified on Windows / CPython 3.12.14 (see environment notes at the bottom).

# Demonstrate pdb non-interactively by feeding a scripted command sequence and inspecting variables at a breakpoint
import subprocess, sys, textwrap, pathlib, tempfile

target = textwrap.dedent('''
def accumulate(xs):
    total = 0
    for i, x in enumerate(xs):
        total += x * i
    return total
print("Result:", accumulate([5, 6, 7, 8]))
''')
path = pathlib.Path(tempfile.mkdtemp(prefix="tutorial-pdb-")) / "bp_demo.py"
path.write_text(target, encoding="utf-8")

commands = "\n".join([
    "b 5, i == 2",      # Conditional breakpoint: pause only when i == 2
    "c",                # Continue execution until breakpoint
    "p i, x, total",    # Print local variables
    "where",            # Inspect call stack
    "c",                # Continue until program exit
    "q",
]) + "\n"
out = subprocess.run([sys.executable, "-X", "utf8", "-m", "pdb", str(path)], input=commands,
                     capture_output=True, text=True, encoding="utf-8", timeout=10)
print(out.stdout.replace(str(path), "bp_demo.py"))

Recorded output (local user directory replaced with a display placeholder; full log linked below):

> <USER_HOME>\appdata\local\temp\tutorial-pdb-8wxpc2j6\bp_demo.py(2)<module>()
-> def accumulate(xs):
(Pdb) Breakpoint 1 at <USER_HOME>\appdata\local\temp\tutorial-pdb-8wxpc2j6\bp_demo.py:5
(Pdb) > <USER_HOME>\appdata\local\temp\tutorial-pdb-8wxpc2j6\bp_demo.py(5)accumulate()
-> total += x * i
(Pdb) (2, 7, 6)
(Pdb)   <USER_HOME>\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\lib\bdb.py(627)run()
-> exec(cmd, globals, locals)
  <string>(1)<module>()
  <USER_HOME>\appdata\local\temp\tutorial-pdb-8wxpc2j6\bp_demo.py(7)<module>()
-> print("Result:", accumulate([5, 6, 7, 8]))
> <USER_HOME>\appdata\local\temp\tutorial-pdb-8wxpc2j6\bp_demo.py(5)accumulate()
-> total += x * i
(Pdb) Result: 44
The program finished and will be restarted
> <USER_HOME>\appdata\local\temp\tutorial-pdb-8wxpc2j6\bp_demo.py(2)<module>()
-> def accumulate(xs):
(Pdb)

The conditional breakpoint pauses execution only when i == 2. The output shows the local variable tuple (2, 7, 6) and the call chain at that frame; commands are piped via stdin into pdb using an isolated temporary directory and a timeout guard.

Common Pitfalls

  • Committing breakpoint() into production repositories: A production worker will hang waiting for terminal input. Enable Ruff rule T100 in CI to catch stray debugger calls: https://docs.astral.sh/ruff/rules/debugger/
  • Giving up on multiprocess or remote environments: For remote or containerized debugging, use debugpy (the Python debugger backend powering VS Code): https://github.com/microsoft/debugpy
  • Only ever pressing "next" (n): Combining conditional breakpoints, r (run until return), and u/d (navigating up and down stack frames) saves substantial time.
  • Misdiagnosing concurrency or async bugs under a debugger: Pausing a thread alters execution timing and can make race conditions disappear ("Heisenbugs"), where structured logs are more reliable.

Connection to AI Development

  • Debugging model training: Dropping a breakpoint inside forward() to inspect tensor shapes or check for NaN values layer by layer is one of the fastest ways to isolate model bugs.
  • Post-mortem debugging in Jupyter: Running the %debug magic command right after an exception opens an interactive post-mortem debugger at the failing frame: https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-debug
  • Debugging Agent / LLM tool calls: Setting a breakpoint at the entry of a tool handler lets you inspect the exact arguments generated by the model—often revealing subtle schema mismatches in the model's JSON payload.

Further Reading

Comprehension Check

If you evaluate a function with side effects while paused at a breakpoint, is that purely passive observation?

Reference answer: No. Evaluating a function call can write files, mutate in-memory objects, or send network requests, changing the live state of the program being debugged.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 14_breakpoint.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram