breakpoint()

The built-in breakpoint() function inserts breakpoints into your code, allowing you to enter a debugging session at the point where the function is called. This function provides a flexible and intuitive way to integrate debugging into your workflow, using the default Python debugger pdb or any other debugger configured via the PYTHONBREAKPOINT environment variable:

Python division.py
def divide(a, b):
    breakpoint()  # Pause here to inspect arguments
    return a / b

# Usage
a, b = 0, 1
print(divide(a, b))
Shell
$ python3 division.py
> /home/rp/division.py(2)divide()
-> breakpoint()  # Pause here to inspect arguments
(Pdb)

breakpoint() Signature

Python Syntax
breakpoint(*args, **kws)

Arguments

Argument Description
*args Positional arguments passed to the debugging hook.
**kws Keyword arguments passed to the debugging hook.

Return Value

  • By default, breakpoint() doesn’t return any value as it calls pdb.set_trace(), entering an interactive debugging session.
  • The return value can vary if a custom debugger or function is used via the PYTHONBREAKPOINT environment variable.

breakpoint() Examples

With the default configuration:

Python area.py
def calculate_area(length, width):
    area = length * width
    breakpoint()  # Pause here to inspect variables
    return area

# Usage
result = calculate_area(5, 3)
print(f"The area is: {result}")

breakpoint() Common Use Cases

The most common use cases for the breakpoint() function include:

  • Debugging code to identify errors or unexpected behavior
  • Customizing the debugging environment by specifying different debuggers
  • Integrating debugging into continuous integration or development pipelines

breakpoint() Real-World Example

Consider a scenario where you’re debugging a function that calculates the reciprocal of a number but sometimes encounters a division by zero error. You can use breakpoint() to investigate:

Python reciprocal.py
def reciprocal(value):
    breakpoint()  # Inspect the input value
    return 1 / value

# Usage
print(reciprocal(2))
print(reciprocal(0))

By running this code, you’ll enter the debugger right before the division occurs, allowing you to inspect the argument and the program’s state. This helps you identify and fix issues like division by zero.

Tutorial

Python Debugging With Pdb

In this hands-on tutorial, you'll learn the basics of using pdb, Python's interactive source code debugger. Pdb is a great tool for tracking down hard-to-find bugs and allows you to fix faulty code more quickly.

intermediate tools

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 14, 2024 • Reviewed by Dan Bader