Python breakpoint() Function



The Python breakpoint() function is used for debugging process, it calls sys.breakpointhook() method which triggers the Python debugger that helps in inspecting program execution.

When the Python interpreter reaches the breakpoint() function, it halts the execution at that specific line and allows the user to inspect variables, expressions, and also, step through the code one line at a time.

The breakpoint() is one of the built-in functions which was added with the Python 3.7 version.

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.

breakpoint() Function Examples

Practice the following examples to understand the use of breakpoint() function in Python:

Example: Use of breakpoint() Function

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: breakpoint() inside User-defined Function

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: breakpoint() Function With Exception

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