tpwo.github.io

A personal blog

Python debugging 101: pdb

Written on (updated )

pdb is a simple debugger that comes by default with Python. There are many more advanced alternatives like pudb or ipdb, but pdb is always available out of the box which is a big plus.

breakpoint() was introduced in Python 3.7. Before that, import of pdb and calling a function that creates a breakpoint was required.

pdb commands

  • h / help – display available commands
  • c / continue – continue running the code until the end
  • q / quit – quit program by raising BdbQuit exception

l / list

Prints lines of code around the line that is about to be run (marked with an arrow). Pressing enter will list even more file. list . will reset the view to the original (i.e. some lines before and after a line with arrow).

ll

Long list, prints more lines of code. Pressing enter has no effect. There is no support for dot from this reason.

w / where

Displays a call stack that led to the execution of the given code.

u / up & d / down

Goes up or down one stack frame. An arrow showed with where is updated to account for the new position. Also, list will print the code around the current stack frame.

up and down accept step parameter, e.g. up 3 will go up by three stack frames.

p & pp

For printing and pretty printing. The latter is especially helpful when printing more complex data structures.

n / next

Goes to the next line.

Whenever, a debugger returns it prints --Return-- to the screen, and pauses right after the return value. Pressing n again will go to the next function.

s / step

Goes inside a function call.

r / return

Goes directly to the return statement of the current function. Useful to quickly exit functions that we are not interested in debugging.

Summary

There are a lot of more features that can be used, e.g. creating breakpoints from pdb, but above I described the basics that should be useful most of the time.

For conditional breakpoints you can use Python if and hide breakpoint under a certain condition.

I really recommend this video from Anthony Sottile if you want to learn more and see how to use pdb in practice.