Sub topic 12
Saving your setup in a .pdbrc file
This chapter assumes you can start a pdb session with breakpoint() or python -m pdb, and that you know the basic commands (p, pp, n, s, c, l). It also assumes you know what an environment variable is and where your home directory is. If you keep typing the same commands at every (Pdb) prompt, a .pdbrc file can run them for you.
What a .pdbrc file is
A .pdbrc file is a plain text file of pdb commands. When pdb starts, it reads the file and runs each line as if you had typed it at the (Pdb) prompt.
The rules are short:
- One command per line.
- Lines that start with
#are comments. - Blank lines are ignored.
- A line that starts with
!is run as a Python statement in the current frame. - Any pdb command works, including
alias,break,next, andcontinue.
Since Python 3.2, a .pdbrc file may also contain commands that resume execution, such as continue or next. Earlier versions ignored them.
Where pdb looks for the file
pdb checks two locations and reads both if both exist. The home directory file is read first, then the file in the current working directory.
| Location | Typical use | Read order |
|---|---|---|
| `~/.pdbrc` (your home directory) | Personal aliases and habits for every project | First |
| `./.pdbrc` (the directory you launched Python from) | Project-specific setup, such as breakpoints | Second |
Because the project file is read second, its lines run later. If both files define an alias with the same name, the project definition replaces the personal one. "Current directory" means where you ran the python command. It does not mean the directory containing your script.
The file is read when the debugger object is created, but the lines run when the program first stops and pdb has a frame to work with. That is why ! statements and aliases can refer to your program's variables.
A first useful file: aliases
The most common use of .pdbrc is the alias command. An alias is a short name for a longer command. Inside the alias body, %1, %2, and so on stand for the arguments you type, and %* stands for all of them.
Create ~/.pdbrc with this content:
# ~/.pdbrc: personal pdb setup
# Pretty-print all local variables
alias pl pp locals()
# Print every attribute of an object, one per line
alias pi for k, v in vars(%1).items(): print(f"%1.{k} = {v!r}")
# Print an object's type
alias pt p type(%1)
# Print the attributes of self
alias ps pi selfNow try it with this script, saved as cart.py:
class Cart:
def __init__(self):
self.items = []
self.discount = 0.1
cart = Cart()
cart.items.append("pen")
breakpoint()
print(cart.items)Run python cart.py and type the aliases at the prompt:
> /home/you/cart.py(10)<module>()
-> print(cart.items)
(Pdb) pi cart
cart.items = ['pen']
cart.discount = 0.1
(Pdb) pt cart
<class '__main__.Cart'>
(Pdb) c
['pen']pi cart expanded to a one-line for loop with cart substituted for each %1. You can see the expansion by typing alias pi with no body, which prints the stored definition. Typing alias alone lists every alias that is currently defined.
Running Python statements from the file
A line that starts with ! is executed as Python in the frame where the program stopped. This is useful for small helpers, but it comes with a catch: the statement runs in your program's namespace. An import in .pdbrc adds a name to the frame you are debugging.
# Make a helper available in whatever frame you stop in
!import pprint as _pp
alias pj _pp.pprint(%1, width=60)The leading underscore lowers the chance of shadowing a name your program uses. Even so, a program's own variable called _pp would be overwritten. Keep ! lines to a minimum, and prefer aliases built from pdb's own commands where you can.
Project files: stored breakpoints
A .pdbrc in your project directory can set breakpoints you want every time you debug that code. Place this in ./.pdbrc:
# ./.pdbrc: project setup for the billing package
break billing/invoice.py:88, total < 0
alias pinv pp %1.__dict__Two details matter here:
- File names in
breakcommands are resolved relative to where you launched Python, so the project file works when you start from the project root. - If the breakpoint is in a file pdb cannot find, pdb prints an error at startup and goes on with the other lines.
Because .pdbrc can run continue, a project file can also skip the initial stop when you run python -m pdb script.py. The last line below makes pdb run to the first breakpoint instead of halting on line 1:
break billing/invoice.py:88
continuePassing one-off commands with -c
When you want startup commands for a single run only, use the -c option of python -m pdb. It behaves like a line in .pdbrc and can be repeated:
python -m pdb -c "break cart.py:10" -c "continue" cart.pyCommands given with -c run after the .pdbrc files have been read. This is a good choice for a one-time experiment that does not belong in a saved file.
Turning the file off
Sometimes a .pdbrc gets in the way: a stored continue skips a stop you wanted, or a project file breaks a reproduction. When you create the debugger yourself, pass readrc=False:
import pdb
def total(values):
s = 0
for v in values:
s += v
pdb.Pdb(readrc=False).set_trace()
return s
print(total([1, 2, 3]))Here pdb ignores both .pdbrc files and the prompt appears with a clean state. The breakpoint() built-in creates its own debugger with the default settings, so it always reads the files. To avoid the files with breakpoint(), move or rename the file, or set PYTHONBREAKPOINT to a function that builds a Pdb(readrc=False).
Safety and sharing
A .pdbrc in the current directory is run without any prompt. A hostile repository could ship one containing ! lines that run arbitrary Python as soon as you debug inside it. The same applies to import lines in any file you did not write. Treat it like any file that executes code:
- Read a
.pdbrcbefore you start pdb in a checkout you do not trust. - Keep personal aliases in
~/.pdbrc, which only you control. - Commit a project
.pdbrconly if the team agrees on it. Otherwise add it to.gitignore. - Do not put secrets, such as tokens in
!statements, in either file.
Common errors
- Alias works in the file but not at the prompt. Check that the alias body is valid at the prompt. Type the expanded text by hand to see the error.
- Nothing happens. pdb reads
./.pdbrcfrom the directory where you ranpython, not from the script's directory. Runpwdand compare. - A stored
continueruns too early. Lines run in order at the first stop. Putbreaklines beforecontinue. - Names shadowed after a
!import. The import landed in the program's frame. Use a name with an underscore prefix or avoid the import. - A
%1that stays literal.%1is replaced only inside analiasbody. In a normal command it is just text.
Exercise
You want every pdb session in any project to have a command pk that prints the keys of a dictionary variable you pass, for example pk config. You also want one specific project to stop at line 40 of app/main.py whenever retries > 2. Which files do you create, and what lines go in each?
Show answer
Put the alias in ~/.pdbrc, because that file is read for every session: alias pk p sorted(%1.keys()). Put the breakpoint in .pdbrc in the project root, and launch Python from that directory: break app/main.py:40, retries > 2. The home file is read first and the project file second, so both are active in that project. Typing pk config then prints the sorted keys of config.