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.
# my_script.py 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 my_script.py, it will stop at the breakpoint and start the debugger session:
python my_script.py --Return-- > my_script.py(6)<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.
- h (elp): Print the list of available commands
- l (ist): List source code for the current file
- w (here): Print a stack trace, with the most recent frame at the bottom
- q (uit): Quit from the debugger
- p expression: Evaluate the expression in the current context and print its value
- n (ext): Continue execution until the next line in the current function is reached or it returns (The difference between next and step is that step stops inside a called function, while next executes called functions, only stopping at the next line in the current function)
- s (tep): Execute the current line, stop at the first possible occasion (either in a function that is called or on the next line in the current function)
- c (ontinue): Continue execution, only stop when a breakpoint is encountered
With these commands, we can step through the code, print expressions, and track down our bug 😊.
Join My Newsletter! Get Python and ML tips emailed directly to your inbox. Each month you’ll get a summary of all the content I created, including the newest videos, articles, promotions, tips, and more.
Learn all the necessary basics to get started with TensorFlow 2 and Keras.
Learn all the necessary basics to get started with this deep learning framework.
Implement popular Machine Learning algorithms from scratch using only built-in Python modules and numpy.