Sub topic 5
Inspecting variables and source: p, pp, args, list, display
Once a program is paused at the (Pdb) prompt, the next question is what state it holds. This chapter covers the commands that answer it: p, pp, args, whatis, list, longlist, display, and a few related ones.
It assumes you can already start a session with breakpoint() and step with n, s, and c. It also assumes you are comfortable with Python's repr() and with how local variables and function arguments work.
The example program
The examples below use one script, shop.py. It has a deliberate bug: the caller passes 8 as the tax rate instead of 0.08.
def summarize(orders, tax_rate):
subtotal = 0
breakpoint()
for order in orders:
subtotal += order["price"] * order["qty"]
return subtotal * (1 + tax_rate)
orders = [
{"sku": "A1", "price": 10.0, "qty": 2},
{"sku": "B2", "price": 4.5, "qty": 4},
{"sku": "C3", "price": 2.0, "qty": 10},
]
print(summarize(orders, 8))Run it with python shop.py. Execution stops after the breakpoint() call, and pdb shows the next line to run:
> /home/me/shop.py(4)summarize()
-> for order in orders:
(Pdb)The first line gives the file, the line number in parentheses, and the function name. The second line is the source line that is about to execute. It has not run yet.
Printing values with p and pp
p expression evaluates the expression in the current frame and prints its repr(). The expression can be anything Python accepts, not only a name.
(Pdb) p subtotal
0
(Pdb) p tax_rate
8
(Pdb) p len(orders)
3
(Pdb) p [o["sku"] for o in orders]
['A1', 'B2', 'C3']pp expression does the same through pprint.pformat. It matters when a value is too wide for one line:
(Pdb) pp orders
[{'price': 10.0, 'qty': 2, 'sku': 'A1'},
{'price': 4.5, 'qty': 4, 'sku': 'B2'},
{'price': 2.0, 'qty': 10, 'sku': 'C3'}]pp sorts dictionary keys, so price comes before sku even though the source lists sku first. A plain p keeps insertion order. If you need to see the real order, use p.
pp locals() shows every local variable at once. This is often the quickest way to see what a function holds. pp globals() is usually too noisy to read, because it includes module internals.
Both commands call your expression's code. p obj.compute() really runs compute(), so side effects such as writes or counter increments happen. Prefer reading attributes over calling methods while you debug.
Arguments and types
args (short form a) prints the arguments of the current function with their current values:
(Pdb) a
orders = [{'sku': 'A1', 'price': 10.0, 'qty': 2}, {'sku': 'B2', 'price': 4.5, 'qty': 4}, {'sku': 'C3', 'price': 2.0, 'qty': 10}]
tax_rate = 8It shows the current value, not the value the caller passed. If the function reassigned an argument, you see the new value.
whatis expression prints the type of an expression. It helps when a value looks right but behaves wrongly, such as a string '8' where you expected the integer 8. p would show quotes, but whatis states it directly:
(Pdb) whatis tax_rate
<class 'int'>
(Pdb) whatis orders[0]["price"]
<class 'float'>retval (alias rv) prints the value returned by the last function that returned. Use it after the r command to see what a call produced.
Running statements and name clashes
If the line you type is not a pdb command, pdb runs it as Python. That means subtotal = 0 at the prompt changes the variable, and you can test a fix before editing the file.
Problems start when a variable has the same name as a pdb command. If your code has a variable called n, c, l, or a, typing it runs the command instead. Use p n to print it. To run a statement that begins with a command name, put ! in front:
(Pdb) !n = 5
(Pdb) p n
5For a longer experiment, interact opens a normal Python prompt that sees the current local and global names. Press Ctrl-D to return to (Pdb). Assignments you make there do not change the paused frame's locals, so use !name = value when you want to modify them.
Reading source: list and longlist
You rarely need to open an editor to know where you are. list (short form l) prints 11 lines of source around the current line. A -> marks the line about to run:
(Pdb) l
1 def summarize(orders, tax_rate):
2 subtotal = 0
3 breakpoint()
4 -> for order in orders:
5 subtotal += order["price"] * order["qty"]
6 return subtotal * (1 + tax_rate)
7
8
9 orders = [
10 {"sku": "A1", "price": 10.0, "qty": 2},
11 {"sku": "B2", "price": 4.5, "qty": 4},The exact spacing varies by Python version. Repeating l continues with the next lines, and the last 3 lines appear on the second call. Three other forms control the window:
l .returns to the 11 lines around the current line, which is useful after you have scrolled away.l 20,40prints lines 20 to 40 of the current file.ll(longlist) prints the whole source of the current function or frame, which saves you from guessing a range.
In listings, a B next to a line number marks a line with a breakpoint, and -> still marks the current line. source expression prints the source of a module, class, or function, for example source summarize.
Watching values with display
Typing p subtotal after every step gets tedious. display expression registers an expression that pdb re-evaluates each time execution stops in the current frame. It prints the value only when it has changed.
(Pdb) display subtotal
display subtotal: 0
(Pdb) n
> /home/me/shop.py(5)summarize()
-> subtotal += order["price"] * order["qty"]
(Pdb) n
> /home/me/shop.py(4)summarize()
-> for order in orders:
display subtotal: 20.0Python versions differ here. Newer releases append the previous value, as in [old: 0], to the changed line.
The remaining display commands:
displaywith no argument lists every registered expression for the current frame.undisplay subtotalremoves one expression.undisplaywith no argument removes them all.
Display expressions belong to a frame. When you step into another function, they do not follow you there. If an expression cannot be evaluated in a frame, such as a name that does not exist yet, pdb reports the error instead of a value.
Choosing the right command
Putting it together
Back at the first stop in shop.py, the result is far too large, and the investigation takes four commands:
ashowstax_rate = 8, which already looks wrong for a rate.display subtotalplus a fewnpresses shows the subtotal growing to 58.0, so the loop is correct.p subtotal * (1 + tax_rate)evaluates to522.0, matching the program's wrong output.!tax_rate = 0.08followed by the samepgives62.64, which confirms the cause.
The bug is in the caller, not in summarize. The debugger let you confirm that without editing the file. Any assignment you make this way lasts only for this run.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Typing a variable name runs a command instead | The name matches a pdb command such as `n`, `c`, `l`, or `a` | Use `p name` or `!name` |
| `l` shows lines far from where you stopped | Repeated `l` calls scrolled the window | Use `l .` |
| `display` prints nothing | The value has not changed since the last stop | This is expected. Use `display` with no argument to list expressions |
| `NameError` after stepping into a function | The name belongs to the previous frame | Print it from that frame, or move with `up` |
| `pp` shows dict keys in a different order | `pp` sorts keys | Use `p` for insertion order |
Exercise
You are stopped in a function with a long list of dictionaries in a local variable called rows. You want to see its contents readably, watch len(rows) as you step, and see the whole function's source. Which three commands do you use, and what does display len(rows) print when the length has not changed since the last stop?
Show answer
Use pp rows for the readable listing, display len(rows) to watch the length, and ll for the whole function's source. When the value has not changed since the last stop, display prints nothing for that expression. It prints only when the value changes.
Exercise
A function has a parameter n, and typing n at the prompt steps to the next line instead of showing the value. How do you print the parameter, and how do you set it to 10 for the rest of this run?
Show answer
Print it with p n (or !n). Set it with !n = 10. The ! prefix tells pdb to treat the line as Python, not as a pdb command.