Intermediate Chapter 168 · 30 min read · Module 13: Python Testing and Debugging
Python Debugger
- After this chapter you can start the debugger with breakpoint() or python -m pdb.
- You can use the commands n, s, c, p, l, b and q.
- You can step through code and inspect variables at each step.
- You can set breakpoints and conditional breakpoints.
- You can use post-mortem debugging after a crash.
Print statements are useful, but they have limits. You must edit the code, run it again, and read a long list of output. A debugger lets you pause the running program, look around, and move forward one line at a time. It is like pressing pause on a film and then stepping frame by frame.
Python comes with a debugger called pdb, short for Python DeBugger. It works in any terminal and needs no installation. Editors such as VS Code and PyCharm have graphical debuggers, but they use the same ideas: breakpoints, stepping and inspecting variables. If you understand pdb, you can use any of them.
The pdb prompt reads commands that you type, and that makes it hard to show in a book. In this chapter the runnable examples feed the commands from a string, so you can see exactly what each command prints. In your own terminal you will simply type the commands.
Starting the debugger
The easiest way is to write breakpoint() at the line where you want to stop. When Python reaches it, the program pauses and shows the (Pdb) prompt. This function exists since Python 3.7. Before that people wrote import pdb; pdb.set_trace(), which you may still see in old code. You can also start a whole script under the debugger with python -m pdb script.py, which stops at the first line.
def average(numbers):
total = sum(numbers)
breakpoint() # the program pauses here
return total / len(numbers)
print(average([4, 6, 8]))At the prompt you type a command and press Enter. Typing p total prints the value of the variable total. Typing c continues running until the next breakpoint or the end. The setting PYTHONBREAKPOINT=0 turns every breakpoint() call off without editing the code.
The most useful commands
| Command | Long name | What it does |
|---|---|---|
| n | next | run the current line, do not enter called functions |
| s | step | run the current line, enter a called function |
| c | continue | run until the next breakpoint |
| p expr | show the value of an expression | |
| pp expr | pretty print | show a big value in a tidy way |
| l | list | show source code around the current line |
| w | where | show the call stack |
| b 12 | break | set a breakpoint at line 12 |
| r | return | run until the current function returns |
| q | quit | stop the debugger and the program |
Any short name in this table also has a long version, and pressing Enter on an empty line repeats the last command. If you want to run Python code that has the same name as a command, for example a variable called n, start the line with !, as in !n = 5.
Stepping through a function
The next example drives pdb with scripted commands so that it can run anywhere. The helper run_pdb sends the commands as if you typed them. In a real terminal pdb also shows the next line of code after each command, marked with ->. The helper hides those lines so the output is short and the same on every computer, and it shows only what p prints. Compare n, which goes over a line, with s, which goes into a function call.
import pdb, io
def run_pdb(func, commands, *args):
out = io.StringIO()
dbg = pdb.Pdb(stdin=io.StringIO(commands), stdout=out)
dbg.use_rawinput = False
dbg.runcall(func, *args)
for line in out.getvalue().splitlines():
line = line.replace("(Pdb) ", "")
if line and not line.startswith(("> ", "-> ")):
print(line)
def add(a, b):
total = a + b
return total * 2
run_pdb(add, "n\np total\nc\n", 2, 3)First the debugger stops at the beginning of add, before the line total = a + b. After n that line has run, so p total prints 5. Finally c lets the function finish.
import pdb, io
def run_pdb(func, commands, *args):
out = io.StringIO()
dbg = pdb.Pdb(stdin=io.StringIO(commands), stdout=out)
dbg.use_rawinput = False
dbg.runcall(func, *args)
for line in out.getvalue().splitlines():
line = line.replace("(Pdb) ", "")
if line and not line.startswith(("> ", "-> ")):
print(line)
def square(x):
return x * x
def calc(v):
y = square(v)
return y + 1
run_pdb(calc, "s\ns\np x\nc\n", 4)Here the first s runs the line that starts at calc. The second s goes into square, and p x shows the argument. If we had used n, the call to square would have run in one go. Use s when you suspect a called function, and n when you trust it.
Breakpoints and conditions
In a loop that runs a thousand times you do not want to press n a thousand times. Set a breakpoint with b line_number, then press c to jump to it. A conditional breakpoint, such as b 8, i == 500, stops only when the condition is true. Typing b alone lists all breakpoints, and cl 1 clears breakpoint number 1.
import pdb, io
def run_pdb(func, commands, *args):
out = io.StringIO()
dbg = pdb.Pdb(stdin=io.StringIO(commands), stdout=out)
dbg.use_rawinput = False
dbg.runcall(func, *args)
for line in out.getvalue().splitlines():
line = line.replace("(Pdb) ", "")
if line and not line.startswith(("> ", "-> ")):
print(line)
def total_of(items):
total = 0
for item in items:
total += item
return total
run_pdb(total_of, "n\nn\nn\nn\np item, total\nc\n", [10, 20])After four steps the loop has gone round once, and p item, total prints a tuple of both values. Printing two values at once is a handy trick. The example shows how to read what the program is doing without changing a single line of the function.
Post-mortem debugging
Sometimes the program crashes and you want to look at the state at the moment of the crash. Running python -m pdb script.py and typing c makes pdb stop at the failure and open a post-mortem session. You can also call pdb.post_mortem() inside an except block. In both cases you can use p to print variables and w to see the call stack, even though the program is already broken.
import pdb
def divide(a, b):
return a / b
try:
divide(5, 0)
except ZeroDivisionError:
pdb.post_mortem() # opens (Pdb) at the failing lineDebugger or print?
Both tools are good. Use print or logging when you want a record over time, such as in a program that runs on a server. Use the debugger when you want to explore: you do not know in advance which variable matters, so you pause and ask many questions. Remember to remove breakpoint() calls before you share your code.
Python syntax
breakpoint()python -m pdb script.pyb 12, i == 500 # conditional breakpointimport pdb
pdb.post_mortem()Real-world applications
- Finding the exact moment a variable gets a wrong value.
- Understanding how an unfamiliar library works by stepping into its code.
- Investigating crashes in a development environment.
- Teaching and learning how a program flows.
Common mistakes
Fix: Search for breakpoint before committing, or set PYTHONBREAKPOINT=0.
Fix: Use s to step into the function, and r to return when you are done.
Fix: Use p n to print it, or start the line with ! to run it as Python.
Fix: Set a breakpoint just before the suspect line and use n one step at a time.
Important tips
- Press Enter on an empty line to repeat the last command.
- Use l to see where you are, and w to see how you got there.
- Use pp for large dictionaries and lists.
- Combine the debugger with a failing test for a repeatable investigation.
Key points summary
- breakpoint() pauses the program and opens pdb.
- n goes over a line, s steps into a call, c continues.
- p prints a value, l lists code, w shows the stack.
- Breakpoints can have conditions.
- Post-mortem debugging inspects a crash.
Exam and interview points
- pdb is the standard library debugger.
- breakpoint() calls pdb.set_trace() by default since Python 3.7.
- Know the commands n, s, c, p, l, b, q.
- PYTHONBREAKPOINT=0 disables breakpoint() calls.
Quick revision
- breakpoint() to pause.
- n next, s step, c continue.
- p value, l list, w where.
- b N sets a breakpoint.
- q quits.
Frequently asked questions
What is the difference between n and s?
Both run one line. If the line calls a function, n runs the whole call and stops at the next line, while s goes inside the function.
How do I quit the debugger?
Type q and press Enter. This also stops the program.
Does breakpoint() work in every Python version?
It was added in Python 3.7. Older versions need import pdb and pdb.set_trace().
Can I change a variable inside the debugger?
Yes. Type a Python statement such as !total = 0, and the program continues with the new value.
Practise this chapter
19 practice questions Take the chapter quiz