Simple Python Debugging with Pdb: Part 1

I’m pretty new with Python, so I was looking around for some debugging tools. At first I dismissed Pdb (Python debugger) as being too primitive, but after seeing a blog post about using Pdb, I decided that I should give it a try.

To get started with Pdb

1. import the pdb module
2. insert a call to the set_trace() method

Here is a simple Python example that calculates and displays a few points on a line. The program is not very interesting, and serves only as a vehicle to talk about debugging.

import pdb

def fun(x):
return 3 * x + 1

pdb.set_trace()
for x in range(2, 9):
y = fun(x)
print(“(x,y) = (“, x, ” ,”, y, “)”)

When I run the code above (test.py), execution stops at the break-point I set just before the start of the for loop. The line that is shown — -> for x in range(2, 9):  — is the next line to be executed.

Following that line is the Pdb prompt, (Pdb)

We’re now ready to enter some commands. Some of the commands that I’ve found most useful are these:
l (lowercase L) or list – list eleven lines of code around the current position
ll (lowercase L’s) or longlist – list all source code for the current function or frame

Most of the Pdb commands have short forms. To see all of the Pdb commands, type h or help at the Pdb prompt. For help on an individual command, type h or help, followed by the command.

Here is the result of typing l (ell) at the Pdb prompt:

Pressing n or typing next takes us to the next line of code. Pressing n again takes us to the print() statement at the end of the loop body.

Another command, s or step, is similar to n (or next), but will step into a function call rather than stepping over it as s does.

In the next screenshot, the current line is the print statement at the end of the loop body.

An important feature of any debugger is the ability to display the value of a variable. This we can do with the p (or print) command. In the screenshot above, the current line is the print statement, which means it is the next statement to execute. The previous statement, “y = fun(x)” has executed, so we can see the value of y and x as shown below.

In the screenshot above, we can see that p y results in a value of 7 and p x results in a value of  2.

In summary:
To use Pdb to debug a Python script:

1. Import the pdb module, with a line near the top of your script.
import pdb
2. Call the Pdb method, set_trace().
pdb.set_trace()
Place the call to this method where you want execution to stop.
3. Get your bearings with l (or list) or ll (or longlist).
4. Move through your code with n (or next) or s (or step).
5. Display a value using p <var>, where <var> is the name of the variable or expression you want to display.
6. For a list of all Pdb commands, type h or help. For help with a specific Pdb command, type h followed by the command, e.g., h break or more simply h b.

The next part discusses setting breakpoints.