HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

8) Debugging Lesson

Python Breakpoint

3 min to complete · By Martin Breuss

In software development, a breakpoint is a flag you can set in your code that allows you to inspect the current state of your script at the specific point where you set the breakpoint.

The Breakpoint Function

Python 3.7 introduced a handy function called breakpoint() that allows you to access an interactive debugger. In an interactive debugging session, you get a chance to inspect the value of all of the variables that are currently defined in your script. This is equivalent to using print() on every single variable while keeping track of what they are. Additionally, you can also interact with these variables beyond just printing them.

All of this is possible with just a single line of code.

To experience the power of an interactive debugger session in a small example, you'll create a small Python script with the following content:

a = 0
b = 42
breakpoint()
a += b
breakpoint()

Save this script as a Python file and execute it as you would usually, through your CLI or your text editor. As soon as your code execution hits a breakpoint() function, it starts the interactive debugging session with pdb, Python's default debugger from the standard library.

Older Python Versions

If you're using a Python version below 3.7, the breakpoint() function won't work. Instead, you'll have to use a less intuitive sequence of commands in your code, as described in the documentation of pdb

The typical usage to break into the debugger from a running program is to insert import pdb; pdb.set_trace() at the location you want to break into the debugger.

Applying this to the short code snippet shown above, it'd look like this:

a = 0
b = 42
import pdb; pdb.set_trace()
a += b
pdb.set_trace()

This is less intuitive than breakpoint() and introduces a messy pattern of using an import statement somewhere in the middle of your code.

Colorful illustration of a light bulb

Info: If you're using a Python version below 3.7, update to a more modern version of Python. If you have to work with a lower version, you can use import pdb; pdb.set_trace() to set a breakpoint.

You'll look into what happens once the debugger session has started and how to interact with it in the next lesson.