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.5. Mastering IPython's configuration system

In [ ]:
%%writefile random_magics.py
# NOTE: We create the `random_magics.py` file here so that 
# you don't have to do it...
from traitlets import Int, Float, Unicode, Bool
#from IPython.utils.traitlets import Int, Float, Unicode, Bool # IPython < 4.x
from IPython.core.magic import (Magics, magics_class, line_magic)
import numpy as np

@magics_class
class RandomMagics(Magics):
    text = Unicode(u'{n}', config=True)
    max = Int(1000, config=True)
    seed = Int(0, config=True)
    
    def __init__(self, shell):
        super(RandomMagics, self).__init__(shell)
        self._rng = np.random.RandomState(self.seed or None)
        
    @line_magic
    def random(self, line):
        return self.text.format(n=self._rng.randint(self.max))
    
def load_ipython_extension(ipython):
    ipython.register_magics(RandomMagics)
  1. We create an IPython extension in a file random_magics.py. Let's start by importing a few objects:
from traitlets import Int, Float, Unicode, Bool #from IPython.utils.traitlets import Int, Float, Unicode, Bool # IPython < 4.x from IPython.core.magic import (Magics, magics_class, line_magic) import numpy as np
  1. We create a RandomMagics class deriving from Magics. This class contains a few configurable parameters.
@magics_class class RandomMagics(Magics): text = Unicode(u'{n}', config=True) max = Int(1000, config=True) seed = Int(0, config=True)
  1. We need to call the parent's constructor. Then, we initialize a random number generator with a seed.
def __init__(self, shell): super(RandomMagics, self).__init__(shell) self._rng = np.random.RandomState(self.seed or None)
  1. Then, we create a line magic %random that displays a random number.
@line_magic def random(self, line): return self.text.format(n=self._rng.randint(self.max))
  1. Finally, we register that magics when the extension is loaded.
def load_ipython_extension(ipython): ipython.register_magics(RandomMagics)
  1. Let's test our extension!
In [ ]:
%load_ext random_magics
In [ ]:
%random
In [ ]:
%random
  1. Our magics command has a few configurable parameters. These variables are meant to be configured by the user in the IPython configuration file, or in the console when starting IPython. To configure these variables in the terminal, we can type in a system shell the following command:
ipython --profile=cookbook --RandomMagics.text='Your number is {n}.' --RandomMagics.max=10 --RandomMagics.seed=1

In that session, we get the following behavior:

In [1]: %load_ext random_magics In [2]: %random Out[2]: u'Your number is 5.' In [3]: %random Out[3]: u'Your number is 8.'
  1. To configure the variables in the IPython configuration file, we have to open the file ~/.ipython/profile_cookbook/ipython_config.py and add the following line:
c.RandomMagics.text = 'random {n}'

After launching IPython, we get the following behavior:

In [ ]:
%random

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).