#!/usr/bin/env python # coding: utf-8 # # Customizing IPython - Extensions # Extensions are just Python modules with a special function: # # ```python # def load_ipython_extension(ip): # do_anything() # ``` # # `%load_ext module` imports the module, and calls `module.load_ipython_extension(ip)` # with the IPython instance. # # This allows modules or standalone extensions to manipulate IPython. # Most often, extensions define new magics or work with the interactive namespace. # # Cython is an example of a package that can be used as an IPython extension. # This defines a few magics for executing Cython code interactively. # In[1]: get_ipython().run_cell_magic('cython', '', '\ncpdef noop():\n pass\n') # In[2]: get_ipython().run_line_magic('load_ext', 'Cython') # In[3]: get_ipython().run_cell_magic('cython', '', 'cimport numpy\n\ncpdef cysum(numpy.ndarray[double] A):\n """Compute the sum of an array"""\n cdef double a=0\n for i in range(A.shape[0]):\n a += A[i]\n return a\n') # In[4]: def pysum(A): """Compute the sum of an array""" a = 0 for i in range(A.shape[0]): a += A[i] return a # In[5]: import numpy as np # In[6]: for sz in (100, 1000, 10000): A = np.random.random(sz) print("Python %i" % sz, end=' ') get_ipython().run_line_magic('timeit', 'pysum(A)') print("np.sum %i" % sz, end=' ') get_ipython().run_line_magic('timeit', 'A.sum()') print("Cython %i" % sz, end=' ') get_ipython().run_line_magic('timeit', 'cysum(A)') # Let's see what Cython's `load_ipython_extension` function looks like # In[7]: import Cython # In[8]: get_ipython().run_line_magic('pinfo2', 'Cython.load_ipython_extension') # In[9]: from Cython.Build.IpythonMagic import CythonMagics get_ipython().run_line_magic('pinfo2', 'CythonMagics') # ## Our own extension # Loading an extension can do as much or as little as you want. # # Since we have been defining our timer magics, let's create an extension to make them available in any IPython session. # In[10]: get_ipython().run_line_magic('pycat', 'soln/mymagics.py') # `%install_ext` is a function that can take any file path or URL, and puts the target into IPYTHONDIR/extensions # In[11]: get_ipython().run_line_magic('install_ext', 'soln/mymagics.py') # In[12]: get_ipython().run_line_magic('load_ext', 'mymagics') # In[13]: import time get_ipython().run_line_magic('tic', '') time.sleep(0.1) get_ipython().run_line_magic('toc', '') # In[14]: get_ipython().run_line_magic('nbrun', '_Sample') # For some example extensions, see [this repository](http://github.com/minrk/ipython_extensions). # # Now we can get our magics with a single `%load_ext` call. # Let's move on to [Configuring IPython](Customizing%20IPython%20-%20Config.ipynb), # so we can see how to load our extension at startup.