Professional Debugging (PDB)
Stop spraying print() statements. Learn to freeze time and inspect your code like a surgeon.
1. The Big Idea (ELI5)
👶 Explain Like I'm 10: The CSI Detective
Imagine a Murder Mystery (A Bug in your Code).
- Print Statements: You run into the room screaming "WHERE ARE YOU?" (Printing variables). If the killer is hiding, you miss him. It's messy and noisy.
- The Debugger (PDB): You are a CSI Detective with a Time Stone. You freeze time exactly when the murder happens (`breakpoint()`). You walk around the frozen room, look in pockets (`p variable`), check fingerprints (`dir()`), and then fast-forward time 1 second (`next`) to see what happens.
2. The Magic Word: `breakpoint()`
In Python 3.7+, you don't need to import anything. Just type `breakpoint()` anywhere, and your code will pause there.
PYTHON
def calculate_tax(income, rate):
tax = income * rate
breakpoint() # <--- PAUSE HERE
return tax - 500
calculate_tax(50000, 0.3)When you run this script, your terminal will change to `(Pdb)`. You are now in control.
3. Essential PDB Commands
Memorize these 5 keys. They are your superpowers.
| Key | Command | Action |
|---|---|---|
| n | next | Run the next line of code. |
| s | step | Step inside a function call. |
| c | continue | Resume execution until the next breakpoint. |
| p | Print a variable (e.g., `p income`). | |
| q | quit | Exit the debugger immediately. |
4. Deep Dive: Post-Mortem Debugging
What if your script runs for 2 hours and then crashes? You can't sit there watching it!Post-Mortem debugging opens the debugger after the crash, at the exact line of death.
PYTHON
# Run your script with this flag
python -m pdb -c continue myscript.py
# OR inside your code:
import pdb
try:
complex_logic()
except Exception:
# Opens PDB automatically when an error occurs!
pdb.post_mortem()5. Inspecting the Unknown: `dir()` and `locals()`
Inside PDB, you can run ANY Python code.
- `locals()`: See every available variable in current scope.
- `dir(obj)`: See all methods/attributes of an object.
- `import math`: Yes, you can even import libraries mid-debug to calculate things!
6. Conditional Breakpoints
Loop runs 1,000 times. Bug happens on number 999. You don't want to hit `n` 999 times.
PYTHON
for i in range(1000):
# Only stop if i is 999
if i == 999:
breakpoint()
process(i)