Luckily, you have many options when debugging in Python. Most of these techniques apply to both IPython and Jupyter Notebook. Thanks to the Jupyter team and other open source contributors for simplifying the debugging process.
If after running any of these cells, the notebook appears to be stuck, it may be because you did not exit the debugger, in which case you will need to restart the kernel.
After an exception has just occurred, you can step into the debugger with the debug command.
If you are working from own machine, make sure to install the
pip install ipdb
""" 1. Uncomment the compute statement below and press SHIFT-ENTER. 2. Uncomment the debug command in the next cell and press CTRL-ENTER. 3. Type adverb and ENTER to examine the value of the adverb variable. 4. Type '' + None and ENTER to recreate the exception. 5. Type help and ENTER to see available commands. 6. Type q and ENTER to exit the debugger. 7. Type ESC and 00 if the notebook is stuck because you forgot to exit the debugger. """ def make_message(verb, adverb=None): phrase = verb + ' vegetables ' + adverb return phrase # make_message('eat')
To enter the debugger automatically whenever there is an exception, run the pdb command. Run it again to toggle the setting.
To walk through specific code, use
""" 1. Uncomment the set_trace statement below and press CTRL-ENTER. 2. Type n and ENTER until you reach the join_sorted_words function call. 3. Type words and ENTER to examine the value of the words variable. 4. Type s and ENTER to step into the join_sorted_words function. 5. Type u and ENTER to zoom out. 6. Type d and ENTER to zoom in. 7. Type q and ENTER to exit the debugger. 8. Type ESC and 00 if the notebook is stuck because you forgot to exit the debugger. """ def decode_message(x): # from IPython.core.debugger import set_trace; set_trace() scrambled_phrase = x.strip() words = scrambled_phrase.split() decoded_phrase = join_sorted_words(words) return decoded_phrase.capitalize() + '!' def join_sorted_words(words): sorted_words = sorted(words) return ' '.join(sorted_words) decode_message(' do can it anyone ')
If you prefer the full set of features available in IPython, use
""" 1. Uncomment the embed statement below and press CTRL-ENTER. 2. Type whos and ENTER to see the current namespace. 3. Type quit and ENTER to exit the interpreter. """ def make_variables(): x = 1 y = 2 z = 3 # from IPython import embed; embed() make_variables()
When debugging from the terminal, our favorite debuggers are
pip install ipdb pudb
They share the standard
import ipdb; ipdb.set_trace() import pudb; pudb.set_trace()
There is a useful
sticky command in
ipdb that displays a large segment of code around the current execution point.
pip install pdbpp
Then you can use the standard
set_trace command but it will start
pdbpp instead of
import pdb; pdb.set_trace()