This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.

# 1.4. Creating an IPython extension with custom magic commands¶

1. Let's import a few functions from the IPython magic system.
In [ ]:
from IPython.core.magic import (register_line_magic,
register_cell_magic)

1. Defining a new line magic is particularly simple. First, let's create a function that accepts the contents of the line (except the initial %-prefixed magic command). The name of this function is the name of the magic. Then, let's decorate this function with @register_line_magic. We're done!
In [ ]:
@register_line_magic
def hello(line):
if line == 'french':
print("Salut tout le monde!")
else:
print("Hello world!")

In [ ]:
%hello

In [ ]:
%hello french

1. Let's create a slightly more useful cell magic %%csv that parses a CSV string and returns a Pandas DataFrame object. This time, the function takes as argument the first line (what follows %%csv), and the contents of the cell (everything in the cell except the first line).
In [ ]:
import pandas as pd
#from StringIO import StringIO  # Python 2
from io import StringIO  # Python 3

@register_cell_magic
def csv(line, cell):
# We create a string buffer containing the
# contents of the cell.
sio = StringIO(cell)
# We use Pandas' read_csv function to parse
# the CSV string.

In [ ]:
%%csv
col1,col2,col3
0,1,2
3,4,5
7,8,9


We can access the returned object with _.

In [ ]:
df = _
df.describe()

1. The method we described is useful in an interactive session. If you want to use the same magic in multiple notebooks, or if you want to distribute it, you need to create an IPython extension that implements your custom magic command. Let's show how to do that. The first step is to create a Python script (csvmagic.py here) that implements the magic.
In [ ]:
%%writefile csvmagic.py
import pandas as pd
#from StringIO import StringIO  # Python 2
from io import StringIO  # Python 3

def csv(line, cell):
sio = StringIO(cell)

"""This function is called when the extension is loaded.
It accepts an IPython InteractiveShell instance.
We can register the magic with the register_magic_function
method of the shell instance."""
ipython.register_magic_function(csv, 'cell')

1. Once the extension is created, we need to import it in the IPython session. The %load_ext magic command takes the name of a Python module and imports it, calling immediately load_ipython_extension. Here, loading this extension automatically registers our magic function %%csv. The Python module needs to be importable. Here, it is in the current directory. In other situations, it has to be in the Python path. It can also be stored in ~\.ipython\extensions which is automatically put in the Python path.
In [ ]:
%load_ext csvmagic

In [ ]:
%%csv
col1,col2,col3
0,1,2
3,4,5
7,8,9


Finally, to ensure that this magic is automatically defined in our IPython profile, we can instruct IPython to load this extension at startup. To do this, let's open the file ~/.ipython/profile_default/ipython_config.py and let's put 'csvmagic' in the c.InteractiveShellApp.extensions list. The csvmagic module needs to be importable. It is common to create a Python package implementing an IPython extension, which itself defines custom magic commands.

You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).

IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).