Sub topic 2
Inspecting variables and source: `p`, `pp`, `args`, `list`, `display`
Assume you can run Python scripts, read tracebacks, and use breakpoint() or python -m pdb. This chapter focuses on examining the current program state and controlling where execution pauses.
Inspecting variables and source
At the (Pdb) prompt, p evaluates and prints a Python expression. pp prints it in a more readable format. args prints the current function's arguments. list shows source code near the current line, while ll shows the whole current function.
(Pdb) p total
(Pdb) pp records
(Pdb) args
(Pdb) list
(Pdb) ll
(Pdb) display total / len(values)
(Pdb) undisplay 1A display expression is evaluated whenever execution stops in the current frame. This helps you watch a changing value without repeatedly typing the expression. p and pp inspect the value only once.
Moving through the call stack
A stack frame is one active function call. where or w lists the frames and marks the current one. up moves to the caller. down returns toward the function that is currently running.
Use p after moving frames to inspect variables belonging to that function. The current frame determines which locals and arguments are available.
Managing breakpoints
Breakpoints pause execution at selected locations. You can create and manage them from the prompt.
(Pdb) b 12
(Pdb) b app.py:30
(Pdb) b process_item
(Pdb) b
(Pdb) disable 1
(Pdb) enable 1
(Pdb) cl 2
(Pdb) clThe b command lists breakpoints when used without a location. disable preserves a breakpoint but prevents it from stopping execution. cl clears one breakpoint or all breakpoints.
Conditions and ignore counts
A conditional breakpoint stops only when its condition is true. An ignore count skips a breakpoint a specified number of times before stopping.
(Pdb) b app.py:30, count > 3
(Pdb) ignore 1 5The condition is evaluated in the frame where the breakpoint occurs. Use conditions to focus on the failing item instead of stopping on every loop iteration.
Exercise
Which command would stop at line 30 only when user_id equals 42?
Show answer
(Pdb) b app.py:30, user_id == 42