Using pdb for Step-Through Debugging in Python | Python tutorials on BeingSkilled

Python offers a built-in module called pdb (Python Debugger) that allows you to step through your code interactively. It's an essential tool for identifying logic errors, inspecting variable values, and controlling the flow of execution during runtime.

Unlike print() statements, pdb gives you a more powerful, granular way to pause your program and inspect what’s happening at each stage.

1. Why Use pdb?

  • Pause execution at any line of code
  • Inspect and modify variable values live
  • Step through the code line by line
  • Navigate through functions and loops

2. How to Import and Use pdb

To use the debugger, import the pdb module and insert pdb.set_trace() where you want to start debugging.

import pdb

def divide(a, b):
    pdb.set_trace()  # Pauses execution here
    return a / b

print(divide(10, 2))

Once the code reaches pdb.set_trace(), it enters interactive mode.

3. Common pdb Commands

Command Description
l (list) Show where you are in the code
n (next) Execute the next line
s (step) Step into a function
c (continue) Continue execution until next breakpoint
q (quit) Quit the debugger
p var Print value of var
! code Execute any Python code

4. Example: Debugging a Simple Function

import pdb

def calculate_discount(price, discount):
    pdb.set_trace()
    final_price = price - (price * discount)
    return final_price

amount = calculate_discount(200, 0.15)
print(f"Discounted Price: {amount}")

Once you hit pdb.set_trace(), use commands like n to step through or p price to check variable values.

5. Setting Breakpoints Without Modifying Code

You can also start a Python script in debug mode from the command line using:

python -m pdb script_name.py

This is useful if you don’t want to modify your code to insert set_trace().

6. Conditional Breakpoints

You can pause execution based on a condition:

import pdb

for i in range(5):
    if i == 3:
        pdb.set_trace()
    print(i)

7. Use Inside Try-Except Blocks

Catch and debug exceptions interactively:

try:
    result = 10 / 0
except Exception as e:
    import pdb; pdb.set_trace()
    print(f"Error: {e}")

8. Alternative: breakpoint() (Python 3.7+)

Instead of writing import pdb; pdb.set_trace(), you can simply write:

breakpoint()

This is equivalent and automatically invokes the default debugger (pdb by default).

9. Tips for Effective pdb Usage

  • Use p to check variable values.
  • Use l to view surrounding lines of code.
  • Step carefully with n and s to avoid skipping logic.
  • Use q to exit the debugger quickly.

10. Final Thoughts

pdb is a powerful yet lightweight tool that every Python developer should know. It allows you to pause, inspect, and control your program while it runs, making it easier to understand and fix bugs. While it's great for small to mid-size projects, it can be integrated into larger applications and IDEs as well.