Debugging tips for python
Here are some useful debugging tips I have learned. Please email me if any of the text can be clarified or if you know of other (or better) methods.
Entering and using a debugger prompt
- Entering a debugger:
- Python script:
import IPython; IPython.core.debugger.set_trace()is the IPython equivalent of MATLAB'skeyboard. You can add this line in a python script and the script's execution will be paused at that line giving you anipdbprompt. - Python script:
import pdb; pdb.set_trace()is thepdbequivalent of the above. - Jupyter notebook: The above commands can be used within functions defined in a Jupyter notebook and will also work when calling external functions from a notebook. If you want to debug an error raised in a Jupyter notebook, use the
%debugmagic in a new cell to drop into an debugger prompt that will let you inspect the program's state. - pytest:
pytest --pdb test.pywill drop you into apdbprompt when a test fails.
- Python script:
- Many commands to inspect your programs state are available at a debugger prompt . You can use
up,downand other commands to navigate the stack. Typehorhelpto see all available commands. Usually, I end up typeuporuto navigate up the stack to a function call I recognize, inspect the arguments of that function call (see below) and then movedown(ord) if needed. - If you have variables with the same names as the debugging commands (e.g.
args), you will need to uselocals()['args']to inspect the value of variableargs(sincelocals()is adictcontaining a mapping of local variable names to their respective objects, see docs). - You can make interactive matplotlib plots at a debugging prompt but no drawing will actually happen unless you also call
plt.pause(1).import matplotlib.pyplot as pltis required prior to runningplt.pause. See this Github comment for details.