0
0
PythonHow-ToBeginner · 3 min read

How to Set Breakpoint in Python for Debugging

In Python, you can set a breakpoint by inserting the breakpoint() function call where you want the program to pause. This opens the debugger, allowing you to inspect variables and step through code interactively.
📐

Syntax

The simplest way to set a breakpoint in Python is to use the breakpoint() function. When Python reaches this line, it pauses execution and opens the debugger.

  • breakpoint(): Pauses the program and starts the debugger.

This function is available in Python 3.7 and later.

python
breakpoint()
💻

Example

This example shows how to use breakpoint() to pause the program and inspect variables during execution.

python
def add_numbers(a, b):
    result = a + b
    breakpoint()  # Program will pause here
    return result

sum_value = add_numbers(5, 7)
print(f"Sum is {sum_value}")
Output
Sum is 12
⚠️

Common Pitfalls

Some common mistakes when setting breakpoints in Python include:

  • Using breakpoint() in Python versions earlier than 3.7, where it is not available.
  • Forgetting to remove or comment out breakpoints in production code, which can pause the program unexpectedly.
  • Not knowing how to use the debugger commands after hitting a breakpoint.

For older Python versions, you can use the pdb module manually:

python
import pdb

pdb.set_trace()  # Older way to set breakpoint

# Correct usage in Python 3.7+:
breakpoint()
📊

Quick Reference

CommandDescription
breakpoint()Pause execution and start debugger (Python 3.7+)
import pdb; pdb.set_trace()Pause execution and start debugger (older Python versions)
nStep to next line in debugger
cContinue execution until next breakpoint
qQuit debugger and stop program

Key Takeaways

Use breakpoint() to set breakpoints easily in Python 3.7 and later.
For older Python versions, use import pdb; pdb.set_trace() to pause execution.
Remember to remove breakpoints from production code to avoid unexpected pauses.
Learn basic debugger commands like n (next), c (continue), and q (quit) for effective debugging.