Back to results for “Debugging”
Python › Debugging & Profiling

How do you use conditional breakpoints in pdb to pause execution only when a specific condition is met, avoiding manually stepping through many unrelated iterations?

Advanced

Answer

Use `pdb.set_trace()` guarded by an 'if' condition directly in your code (the simplest approach), OR set a conditional breakpoint via the 'break' command with a trailing condition when running the debugger interactively (e.g., `break 42, x > 100`), pausing only when that specific condition becomes true.
def process_items(items):
    for i, item in enumerate(items):
        if item.value > 1000:  # only pause for the specific problematic case
            breakpoint()
        process(item)

# Or interactively in pdb: break myfile.py:42, item.value > 1000
Real-world example Debugging a bug that only manifests for a specific, hard-to-reach value deep inside a large loop, without manually stepping through every prior iteration.

Common follow-ups: How do you set a conditional breakpoint directly from the interactive pdb prompt using the 'break' command's condition syntax?