Python breakpoint() Function



The Python breakpoint() function is a built-in function that was introduced with the release of Python 3.7. This function is used in the debugging process of Python programs. Internally, it calls the sys.breakpointhook() method which triggers the Python debugger that helps in inspecting program execution.

Whenever we insert the breakpoint() function at any specific point into our code and execute it, the interpreter will halt at that line and allow users to inspect variables, expressions, and also, step through the code one line at a time.

Syntax

Following is the syntax of the Python breakpoint() function −

breakpoint()

Parameters

The Python breakpoint() function does not accept any parameter.

Return Value

The Python breakpoint() function does not return any value.

Examples

Let's understand how breakpoint() function works with the help of some examples −

Example 1

The following example shows the usage of Python breakpoint() function. Here we are creating a method named 'calc_sum' that accepts a list object and returns sum of its elements. To inspect how it is adding the elements of list, we use the breakpoint() function.

def calc_sum(nums):
   add = 0
   for num in nums:
      add += num
      breakpoint() 
   return add
    
numerics_lst = [1, 2, 3]
res = calc_sum(numerics_lst)
print(f"The total sum is: {res}")

When we run the above program, it displays PDB debugger console where users can interact by passing variable and method names as shown below −

> <main.py>(3)calc_sum()
(Pdb) calc_sum
<function calc_sum at 0x7e5617490720>
(Pdb) add
1
(Pdb) num
1
(Pdb) nums
[1, 2, 3]
(Pdb) n
> <main.py>(4)calc_sum()
(Pdb) num
2
(Pdb)

Example 2

In the code below, we have a calc_sum() method that accepts two arguments and returns their sum. With the help of breakpoint() function, we are enabling the debugger mode to inspect how the sum operation is working.

def calc_sum(a, b):
   return a + b
    
res = calc_sum(51, 49)
breakpoint()  
print(f"The total sum is: {res}")

Following is an output of the above code −

<main.py>(6)<module>()
(Pdb) calc_sum
<function calc_sum at 0x7f9be0b14720>
(Pdb) res
100
(Pdb) 

Example 3

The example below shows how to use breakpoint() in a try-except block in Python. In this code, if the value of divisor is 0, an error is encountered. And, to inspect this error, we are using the breakpoint() function.

def division(x, y):
   try:
      res = x / y
   except ZeroDivisionError:
      print("Error: Division by zero.")
      breakpoint()  
   else:
      print(f"The result is {res}")
        
division(88, 0)

Output of the above code is as follows −

ERROR!
Error: Division by zero.
--Return--
> <main.py>(6)division()->None
(Pdb) x
88
(Pdb) y
0
python_built_in_functions.htm
Advertisements