How to Use the breakpoint() Function for Interactive Debugging in Python
Insert a breakpoint() call into your code to drop into an interactive debugger session where you can inspect variables and step through execution.
Python code
12 linesdef calculate_total(prices, discount=0):
"""Calculates total price with optional discount."""
subtotal = sum(prices)
breakpoint() # Interactive debugging session starts here
final_total = subtotal * (1 - discount)
return final_total
if __name__ == "__main__":
items = [25.50, 13.25, 9.99, 5.75]
result = calculate_total(items, discount=0.1)
print(f"Final total: ${result:.2f}")
Output
Paused at breakpoint() line. Type 'subtotal' to inspect:
subtotal = 54.49
Type 'c' to continue execution:
Final total: $49.04
How it works
The breakpoint() function was introduced in Python 3.7 and provides a built-in shortcut to start the default debugger (typically pdb). When execution reaches the call, it pauses and shows a prompt where you can type commands like p variable to print values, n for next line, s to step into functions, and c to continue. This is significantly faster than adding print statements and re-running the script. The debugger environment respects the PYTHONBREAKPOINT environment variable, so you can override it to use other debuggers or disable it in production.
Common mistakes
- Forgetting to remove breakpoint() calls before deploying to production
- Using breakpoint() in a loop without a condition, causing a pause on every iteration
- Confusing the `q` (quit) command with `c` and accidentally terminating the program
- Not using `PYTHONBREAKPOINT=0` to disable breakpoints in non-interactive environments
Variations
- Use `import pdb; pdb.set_trace()` for compatibility with Python versions before 3.7
- Set the `PYTHONBREAKPOINT` env var to `pdb` for explicit control or to a custom debugger
Real-world use cases
- Troubleshooting a failed calculation inside a data processing script by inspecting intermediate values at runtime.
- Debugging a web framework handler by pausing before returning a response to inspect request context and variables.
- Investigating an unexpected exception in a batch job by breaking just before the failure point to inspect state.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.