Python Quick Tip: Debugger and breakpoint()

Learn how to use the Python Debugger using the breakpoint() function in this Tutorial.

Whenever your code does not work as expected and you want to find out why, you can utilize the Python debugger to detect the bug. It's very simple to get started. You can insert a breakpoint with the breakpoint() function at any position in your code . This is new in Python 3.7, and is equivalent to the older import pdb; pdb.set_trace() command.

# a = int(0.1) b = 3.0 c = a + b breakpoint() # a lot of more code here...

Now when we run this file with python, it will stop at the breakpoint and start the debugger session:

python --Return-- ><module>()->None -> breakpoint() (Pdb)

Now you can apply different commands, e.g., print variables/expressions or execute the script line by line. The most useful commans are listed below. For a full list have a look at the official documentation here.

With these commands, we can step through the code, print expressions, and track down our bug 😊.

Further readings:

FREE VS Code / PyCharm Extensions I Use

🪁 Code faster with Kite, AI-powered autocomplete: Link *

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* These are affiliate links. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses