2 min read

Python Debugging (pdb)

The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level.

Starting the Debugger

Using pdb.set_trace()

You can insert pdb.set_trace() anywhere in your code to pause execution and enter the debugger.

import pdb

def add(a, b):
    pdb.set_trace() # Execution pauses here
    return a + b

print(add(1, 2))

Using breakpoint() (Python 3.7+)

In Python 3.7 and newer, there is a built-in function breakpoint() which calls sys.breakpointhook(), effectively doing the same thing as pdb.set_trace() by default, but is cleaner and more flexible.

def add(a, b):
    breakpoint()
    return a + b

From the Command Line

You can also run a script under the debugger without modifying the source code:

python -m pdb myscript.py

Common Debugger Commands

Once inside the debugger, you can use the following commands:

  • n (next): Continue execution until the next line in the current function is reached or it returns.
  • s (step): Execute the current line, stop at the first possible occasion (either in a function that is called or on the next line in the current function).
  • c (continue): Continue execution, only stop when a breakpoint is encountered.
  • p <expression> (print): Evaluate the expression in the current context and print its value.
  • l (list): List source code for the current file.
  • ll (long list): List the whole source code for the current function or frame.
  • w (where): Print a stack trace, with the most recent frame at the bottom.
  • q (quit): Quit the debugger.

Post-Mortem Debugging

If your program crashes, you can use pdb to inspect the state at the moment of the crash.

import pdb

try:
    1 / 0
except:
    pdb.post_mortem()

programming/python/python