How do I debug Python code with pdb?

· Category: Python Programming

Short answer

pdb is Python's built-in debugger. Insert breakpoint() (Python 3.7+) or import pdb; pdb.set_trace() to pause execution and inspect the program state interactively.

Steps

  1. Add breakpoint() where you want to pause.
  2. Run the script; execution stops at the breakpoint.
  3. Use commands like n (next), s (step), c (continue), p (print), and q (quit).
def factorial(n):
    if n <= 1:
        return 1
    result = n * factorial(n - 1)
    # breakpoint()  # Uncomment to debug here
    return result

print(factorial(5))

Tips

  • l lists source code around the current line.
  • pp pretty-prints variables.
  • until runs until a line number or the current loop finishes.
  • Use python -m pdb script.py to debug from the start of a program.
python -m pdb my_script.py

Common issues

  • Forgetting to remove breakpoint() calls before deploying to production can halt execution.
  • breakpoint() respects the PYTHONBREAKPOINT environment variable, which can be set to 0 to disable it globally.
  • Stepping into standard library code with s can be verbose; use n to stay at your application level.