Python Debugging with pdb
Description
A standard procedure for debugging Python code using the built-in pdb module.
When to use
When you need to step through Python code execution to inspect variables and control flow.
Requirements
- Python installed.
Procedure
- Import
pdb. - Insert
pdb.set_trace()where you want execution to pause. - Run the script.
- Use commands like
n(next),s(step),c(continue), andp <var>(print variable).
Examples
import pdb
def buggy_function():
x = 10
pdb.set_trace()
y = x / 0
return y
Common mistakes / Pitfalls
Do not leave pdb.set_trace() calls in production code. Use conditional breakpoints or logging for production.