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
- Add
breakpoint()where you want to pause. - Run the script; execution stops at the breakpoint.
- Use commands like
n(next),s(step),c(continue),p(print), andq(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
llists source code around the current line.pppretty-prints variables.untilruns until a line number or the current loop finishes.- Use
python -m pdb script.pyto 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 thePYTHONBREAKPOINTenvironment variable, which can be set to0to disable it globally.- Stepping into standard library code with
scan be verbose; usento stay at your application level.