Inspect Execution with Breakpoints and pdb
Core idea
A breakpoint pauses a local program so you can examine its current frame. Run a disposable script with python -m pdb script.py, or insert breakpoint() in trusted local code. In pdb, p expression displays a value, n advances in the current frame, s steps into a call, c continues and q quits. A debugger can execute expressions in the program context.
import pdb, iodef price(qty): return qty * 4out = io.StringIO()debugger = pdb.Pdb(stdin=io.StringIO('p qty\nc\n'), stdout=out, readrc=False, nosigint=True)debugger.use_rawinput = Falseprint(debugger.runcall(price, 3))print('3' in out.getvalue().splitlines()[-1] or '(Pdb) 3' in out.getvalue())The debugger examines qty and resumes. Its transcript is captured rather than requiring an interactive terminal.
Expected output:
12TrueObserve breakpoint hook delegation
import sysold = sys.breakpointhooktry: sys.breakpointhook = lambda: print('pause requested') breakpoint()finally: sys.breakpointhook = oldprint('restored')This substitute illustrates breakpoint delegation without stopping the process.
Expected output:
pause requestedrestoredCommon mistake
Do not leave interactive breakpoints in server jobs. Debugger expressions may mutate state; use read-only inspection first and never attach to a process without authorization.
Practice
Save price in a local script, run pdb and use p qty, n, c and q in separate runs. Remove temporary breakpoints.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Breakpoints and pdb
Check your understanding of breakpoints and pdb.
What is printed?
import sysold=sys.breakpointhooktry: sys.breakpointhook=lambda: print("hit") breakpoint()finally: sys.breakpointhook=oldWhat is printed?
import pdbprint(callable(pdb.set_trace))Which pdb command steps into a call?
Why avoid breakpoints in unattended jobs?