This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
%%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)
random_magics.py
. Let's start by importing a few objects:RandomMagics
class deriving from Magics
. This class contains a few configurable parameters.%random
that displays a random number.%load_ext random_magics
%random
%random
In that session, we get the following behavior:
~/.ipython/profile_cookbook/ipython_config.py
and add the following line:After launching IPython, we get the following behavior:
%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).