Jupyter Tips and Tricks

Just a couple of JupyterLab & Notebook features that I didn’t know a year ago but am now using a lot.

Cell execution history

As long as your Kernel is active, the code of each executed cell is stored in this input history list. Comes in handy when you accidentally deleted a cell etc.

_ih[-5:] # code of the 5 most recently run cells


If you edit the code of an imported module or package, you usually need to restart the notebook kernel or use reload() on the specific module. That can be quite annoying. With the autoreload magic command, modules are automatically reloaded before any of their code is executed.

%load_ext autoreload
%autoreload 2

%debug and the iPython debugger

The easiest way to debug a Jupyter notebook is to use the %debug magic command. Whenever you encounter an error or exception, just open a new notebook cell, type %debug and run the cell. This will open a command line where you can test your code and inspect all variables right up to the line that threw the error. 
Type “n” and hit Enter to run the next line of code (The → arrow shows you the current position). Use “c” to continue until the next breakpoint. “q” quits the debugger and code execution.

%debug magic command

Although not quite up to par with the functionality of the debuggers in IDEs like Pycharm or Visual Studio Code, the iPython debugger is another great option. Import it and use set_trace() anywhere in your notebook to create one or multiple breakpoints. When executing a cell, it will stop at the first breakpoint and open the command line for code inspection. You can also set breakpoints in the code of imported modules, but don’t forget to import the debugger in there as well.

from IPython.core.debugger import set_trace
iPython debugger in action

There is also the relatively new “PixieDebugger” project which wants to offer the “Visual Python Debugger for Jupyter Notebooks You’ve Always Wanted”. I haven’t tested it yet but it sounds very promising!

JupyterLab extensions

It took a while but the first few really useful JupyterLab extensions have become available. JupyterLab is the “next-generation user interface for Project Jupyter”. I just want to highlight and recommend the “Table of contents” and “Variable Viewer” extensions.
To find other extensions you can use the “jupyterlab-extension” search hashtag on github. Also take a look at the “awesome-jupyter” list for even more Jupyter related projects, libraries and resources.

If you found this article useful you can follow me on Twitter @ chrieke where I post about geo, space and Python stuff.