Debugging in Python
Find and fix issues with interactive debuggers, logging, and systematic techniques.
Print and logging
Start with targeted prints; prefer structured logging for real apps.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("value=%s", value)
Built-in debugger (pdb)
Drop into a debugging session at runtime.
import pdb; pdb.set_trace()
# or Python 3.7+: breakpoint()
Common commands:
nnext,sstep in,ccontinuellist,p exprprint,qquit
Post-mortem and tracing
Run post-mortem on exceptions.
import pdb, sys
try:
risky()
except Exception:
_, _, tb = sys.exc_info()
pdb.post_mortem(tb)
IDE/debug tools
Use IDEs (VS Code, PyCharm) for breakpoints, watches, and step-by-step execution.
Profiling vs debugging
Don’t confuse performance issues with logic bugs; use cProfile/line_profiler to find hotspots.
Reproducing issues
- Create small, deterministic repro cases
- Control randomness with fixed seeds
- Isolate environment differences (OS, Python version, installed packages)
Summary
- Use
loggingfor insight;pdb/breakpoint()for interactive debugging - IDE tools help visualize state; create repros and distinguish perf from logic issues