Jupyter Snippet CB2nd 05_config
Jupyter Snippet CB2nd 05_config
1.5. Mastering IPython’s configuration system
%%writefile random_magics.py
from traitlets import Int, Float, Unicode, Bool
from IPython.core.magic import (Magics, magics_class,
line_magic)
import numpy as np
Writing random_magics.py
%%writefile random_magics.py -a
@magics_class
class RandomMagics(Magics):
text = Unicode(u'{n}', config=True)
max = Int(1000, config=True)
seed = Int(0, config=True)
Appending to random_magics.py
%%writefile random_magics.py -a
def __init__(self, shell):
super(RandomMagics, self).__init__(shell)
self._rng = np.random.RandomState(
self.seed or None)
Appending to random_magics.py
%%writefile random_magics.py -a
@line_magic
def random(self, line):
return self.text.format(
n=self._rng.randint(self.max))
Appending to random_magics.py
%%writefile random_magics.py -a
def load_ipython_extension(ipython):
ipython.register_magics(RandomMagics)
Appending to random_magics.py
%load_ext random_magics
%random
'430'
%random
'305'
ipython --RandomMagics.text='Your number is {n}.' \
--RandomMagics.max=10 \
--RandomMagics.seed=1
c.RandomMagics.text = 'random {n}'
from traitlets.config import Configurable
from traitlets import Float
class MyConfigurable(Configurable):
myvariable = Float(100.0, config=True)
c = get_config()
c.MyConfigurable.myvariable = 123.