How to debug a Jupyter/iPython notebook

Here’s how to debug your code when using a Jupyter/iPython notebook.

Use Tracer()(). Here’s an example using a simple function (based on this lucid explanation).

 
def test_debug(y):
    x = 10
    # One-liner to start the debugger here.
    from IPython.core.debugger import Tracer; Tracer()() 
    x = x + y 	 
 
    for i in range(10):
        x = x+i
 
    return x
 
test_debug(10)

When the debugger reaches the Tracer()() line, a small line to type in commands will appear under your cell.

Simply type in the variable names to check the values or run other commands. Below I’ve listed some practical Python PBD commands. More can be found here.

Practical Python PBD debugger commands

Just type them in the window that comes up.

n(ext) line and run this one
c(ontinue) running until next breakpoint
q(uit) the debugger


For reference, I used to used embed(). However, I found that the debugger got stuck in loops. While I could kill it using %exit_raise, for some reason, my matplotlib figures would no longer be displayed until I restarted the session.

So for this reason, I recommend the Tracer()() debugger above rather than the embed() debugger below.

But if you are interested, please keep reading.

Old way to debug [not recommended]

Place this where you want to stop the code:

from IPython import embed; embed()

This should open up a mini terminal within the Jupyter notebook.

You can inspect variables here.

To quit type,

exit

If you’re stuck in a loop,

%exit_raise

Sources and hints from:

from “ruffyen“:

http://stackoverflow.com/questions/28453165/can-i-make-ipython-exit-from-the-calling-code

2 thoughts on “How to debug a Jupyter/iPython notebook”

Questions/comments? If you just want to say thanks, consider sharing this article or following me on Twitter!