Introduced in Python 3.7 (PEP 553), the built-in breakpoint() function drops program execution directly into an interactive debugger prompt. It replaces the traditional import pdb; pdb.set_trace() statement with a cleaner, configurable standard built-in.
Zero-Code Disabling: You can completely disable all breakpoints across an application without modifying code simply by setting the environment variable PYTHONBREAKPOINT=0.
The breakpoint() function takes arbitrary positional and keyword arguments, which it forwards directly to the active breakpoint handler:
breakpoint(*args, **kws)
| Parameter | Type | Description |
|---|---|---|
*args |
Any |
Optional positional arguments forwarded to sys.breakpointhook(). |
**kws |
Any |
Optional keyword arguments forwarded to sys.breakpointhook(). |
Default Behavior: By default, breakpoint() imports the standard Python debugger (pdb) and calls pdb.set_trace(*args, **kws).
When Python encounters breakpoint(), it suspends execution and gives you an interactive command prompt directly in your terminal:
a = 5
print("Value before breakpoint:", a)
breakpoint() # Program pauses here
a = "Welcome to plus2net"
print("Value after breakpoint:", a)
Value before breakpoint: 5
> /home/user/script.py(5)<module>()
-> a = "Welcome to plus2net"
(Pdb) p a
5
(Pdb) c
Value after breakpoint: Welcome to plus2net
At the (Pdb) prompt, typing p a prints the current value of variable a. Typing c continues execution normally.
When paused inside the interactive debugger, you can inspect variables, evaluate expressions, and step through lines using these core commands:
| Command | Shortcut | Description | Example |
|---|---|---|---|
print |
p <expr> |
Evaluate and print the value of an expression or variable. | p total_sum |
pprint |
pp <expr> |
Pretty-print complex dictionaries, lists, or objects. | pp user_record |
next |
n |
Execute the current line and advance to the next line in the current function. | n |
step |
s |
Step into the function call on the current line. | s |
continue |
c |
Resume execution until the next breakpoint or program completion. | c |
list |
l / ll |
Show lines of source code around the current line (ll shows the entire function). |
ll |
where |
w |
Print the full stack trace with the most recent frame at the bottom. | w |
quit |
q |
Immediately abort and exit program execution. | q |
In large loops processing thousands of items, you usually only want to stop when a specific anomalous condition occurs. Simply wrap breakpoint() inside an if statement:
transactions = [120, 450, 310, -25, 890, 200]
for idx, amount in enumerate(transactions):
# Trigger debugger only when an invalid negative amount is encountered
if amount < 0:
print(f"Suspicious transaction detected at index {idx}!")
breakpoint()
# Normal processing
print(f"Processed transaction #{idx}: ${amount}")
You can insert breakpoint() inside class initializers and methods to inspect internal object states and constructor arguments:
class BankAccount:
def __init__(self, account_number, initial_balance):
self.account_number = account_number
self.balance = initial_balance
if self.balance < 0:
breakpoint() # Inspect invalid initial balance
def withdraw(self, amount):
if amount > self.balance:
breakpoint() # Inspect overdraft attempt
self.balance -= amount
return self.balance
account = BankAccount("ACC-4001", 500)
account.withdraw(100)
The major advantage of breakpoint() over older debugging tools is that its behavior is controlled dynamically via the PYTHONBREAKPOINT environment variable without altering application source code:
Set PYTHONBREAKPOINT=0 in your environment or CLI. Python will completely ignore all breakpoint() calls:
$ PYTHONBREAKPOINT=0 python3 app.py
If you prefer richer debuggers such as ipdb (IPython debugger with syntax highlighting) or pudb (visual console interface), specify the callable path:
# Use IPython debugger (ipdb)
$ export PYTHONBREAKPOINT=ipdb.set_trace
# Use visual ncurses debugger (pudb)
$ export PYTHONBREAKPOINT=pudb.set_trace
In Python, breakpoint() simply delegates to sys.breakpointhook(). You can attach a custom function to intercept breakpoints for automated logging, telemetry, or custom diagnostic capture:
import sys
def custom_logger(*args, **kwargs):
print(">>> [DIAGNOSTIC] Breakpoint triggered with arguments:", args, kwargs)
# You could log memory stats, dump thread traces, or send a webhook notification here
# Redirect default hook to our custom function
sys.breakpointhook = custom_logger
temperature = 105.2
if temperature > 100:
breakpoint("High Temperature Alert", current_val=temperature)
>>> [DIAGNOSTIC] Breakpoint triggered with arguments: ('High Temperature Alert',) {'current_val': 105.2}
Let's simulate a data ingestion pipeline with a mock breakpoint inspector that captures anomalous records for debugging without interrupting batch processing, verified with unit assertions:
import sys
# Mock recording list for debugging inspection
debug_log = []
def mock_debugger_hook(*args, **kwargs):
debug_log.append({"args": args, "details": kwargs})
# Temporarily wire hook
original_hook = sys.breakpointhook
sys.breakpointhook = mock_debugger_hook
def process_batch(records):
clean_records = []
for rec in records:
if rec.get("age", 0) <= 0 or rec.get("age", 0) > 120:
# Anomaly detected: trigger breakpoint
breakpoint("INVALID_AGE", record_id=rec["id"], bad_value=rec.get("age"))
continue
clean_records.append(rec)
return clean_records
dataset = [
{"id": 1, "name": "Alice", "age": 29},
{"id": 2, "name": "Bob", "age": -5}, # Invalid
{"id": 3, "name": "Charlie", "age": 34},
{"id": 4, "name": "Diana", "age": 250} # Invalid
]
valid_data = process_batch(dataset)
# Restore default breakpointhook
sys.breakpointhook = original_hook
# Unit Assertions
assert len(valid_data) == 2
assert len(debug_log) == 2
assert debug_log[0]["details"] == {"record_id": 2, "bad_value": -5}
assert debug_log[1]["details"] == {"record_id": 4, "bad_value": 250}
print("Clean records processed:", len(valid_data))
print("Anomalies captured by debugger:", debug_log)
print("All anomaly inspector assertions passed successfully!")
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.