B.4 Tutorial: Debugging in Python with pdb
A debugger is a tool giving us the possibility to open up a code in a certain line so we can investigate our variables s, call stack, ...
The pdb module
Python has a built-in debugger called pdb
. It’s a simple utility with a command-line interface that does the main job. It has all the debugger features we need but we can extend it using ipdb
, which will provide the debugger with features from IPython.
The easiest way to use pdb
is to call it in the code you’re working on.
import pdb
pdb.set_trace()
As soon as the interpreter reaches this line, we’ll receive a command prompt on the terminal where we’re running the program. This is a general Python prompt, but with some new commands.
list(l)
The list(l) command will show you the code line the Python interpreter is currently on. If you want to check a different area of the code, this command has arguments for the first and the last lines to show. If you provide only the number of the first line, you’ll get to see the code around the line you’ve given.
up(p) and down(d)
Up(p) and down(d) are the two commands needed to navigate through the call stack. With the help of these commands, you can see who is calling the current function, for example, or why the interpreter is going this way.
step(s) and next(n)
Another important pair of commands, step(s) and next(n), help you continue the execution of the application line by line. The only difference between these two is that next(n) will only go to the next line of the current function, even if it has a call for another function, but step(s) will go deeper in a case like this.
break(b)
The break(b) command allows you to set up new breakpoints without changing the code.
Python Debugger In Advance
Sometimes we need to set the breakpoint inside a third-party package. Of course, we can open the source code of a library at any time from your virtual environment and add a call for pdb
. But we can run the application from the debugger and set breakpoints without any changes in the source code. To execute the application with the debugger, use the command python -m pdb <python script>
.