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 anipdb
prompt. - Python script:
import pdb; pdb.set_trace()
is thepdb
equivalent 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
%debug
magic in a new cell to drop into an debugger prompt that will let you inspect the program’s state. - pytest:
pytest --pdb test.py
will drop you into apdb
prompt when a test fails.
- Python script:
- Many commands to inspect your programs state are available at a debugger prompt . You can use
up
,down
and other commands to navigate the stack. Typeh
orhelp
to see all available commands. Usually, I end up typeup
oru
to 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 adict
containing 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 plt
is required prior to runningplt.pause
. See this Github comment for details.