Skip to main content
  1. Posts/

My 5 favourite IPython tricks

·390 words·2 mins

These are my 5 favourite tricks I use daily when developing code using IPython, either in the shell or via a Jupyter notebook.

Auto reload #

My all time favourite IPython magic is the auto reload function. This is an extension that automatically reloads modules before executing a cell. Whenever I’m working on a library, I add these 2 lines at the top of my notebook. This means that whenever I change the library I’m working, without having to restart the kernel. Super convenient for debugging.

1
2
%load_ext autoreload
%autoreload 2

Timing #

For some quick performance testing of benchmarking, you can use the built-in time magics.

There are cell magics to time (%%time) or benchmark (%%timeit) the cell. Or you can time (%time) and (%timeit) a single line or function call.

Add virtual environment as Jupyter kernel #

One of my habits is to create a custom virtual environment for every code that I’m working on. These are usually called .venv, and I want to enable these as a kernel in a Jupyter Notebook.

I do this so infrequently that I can never remember the command:

1
2
pip install ipykernel
python -m ipykernel install --user --name .venv

Breakpoint #

I use the breakpoint() function added in Python 3.7 all the time when developing code. Before that I was already calling the IPython.embed module directly, but using a breakpoint() statement is much more convenient.

Especially, because you can customize the debugger by setting the PYTHONBREAKPOINT environment variable. The snippet below will open an IPython shell instead of the default pdb by:

1
PYTHONBREAKPOINT=IPython.embed python my_script.py

Or in your .bashrc:

1
export PYTHONBREAKPOINT="IPython.embed"

Sublime keybindings in Jupyter Notebook #

As a daily Sublime Text user, the ctrl-D command to select the next word is burned into my fingers. One of my annoyances with the default install of Jupyter is that ctrl-D deletes the current line. There are different ways to achieve this ways to enable the Sublime keymap in a Jupyter environment. I found this way to be the most reliable.

Copy this snippet into ~/.config/jupyter/custom/custom.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
require(["codemirror/keymap/sublime", "notebook/js/cell", "base/js/namespace"],
    function(sublime_keymap, cell, IPython) {
        cell.Cell.options_default.cm_config.keyMap = 'sublime';
        cell.Cell.options_default.cm_config.extraKeys["Ctrl-Enter"] = function(cm) {}
        var cells = IPython.notebook.get_cells();
        for(var cl=0; cl< cells.length ; cl++){
            cells[cl].code_mirror.setOption('keyMap', 'sublime');
            cells[cl].code_mirror.setOption("extraKeys", {
                "Ctrl-Enter": function(cm) {}
            });
        }
    } 
);