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 IPython.utils.traitlets import Int, Float, Unicode, Bool
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)
- We create an IPython extension in a file
random_magics.py. Let's start by importing a few objects:
- We create a
RandomMagicsclass deriving fromMagics. This class contains a few configurable parameters.
- We need to call the parent's constructor. Then, we initialize a random number generator with a seed.
- Then, we create a line magic
%randomthat displays a random number.
- Finally, we register that magics when the extension is loaded.
- Let's test our extension!
In [ ]:
%load_ext random_magics
In [ ]:
%random
In [ ]:
%random
- 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:
In that session, we get the following behavior:
- To configure the variables in the IPython configuration file, we have to open the file
~/.ipython/profile_cookbook/ipython_config.pyand add the following line:
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).