importnb imports notebooks as modules. Notebooks are reusable as tests, source code, importable modules, and command line utilities.

BinderDocumentation Status Build StatusPyPI versionPyPI - Python VersionPyPI - FormatPyPI - FormatCondaGitHub tag Code style: black

Installation

pip install importnb

conda install -c conda-forge importnb

importnb for testing

After importnb is installed, pytest will discover and import notebooks as tests.

pytest index.ipynb

`importnb <https://github.com/deathbeds/importnb>`__ imports notebooks as python modules, it does not compare outputs like `nbval <https://github.com/computationalmodelling/nbval>`__.

`importnb <https://github.com/deathbeds/importnb>`__ now captures doctests in every Markdown cell & block string expression. The docstrings are tested with the **–doctest-modules** flag.

pytest index.ipynb --doctest-modules

It is recommended to use importnb with **–nbval** and the –monotonic flag that checks if has notebook has be restarted and re-run.

pytest index.ipynb --nbval --monotonic

importnb for the commmand line

importnb can run notebooks as command line scripts. Any literal variable in the notebook, may be applied as a parameter from the command line.

ipython -m importnb -- index.ipynb --foo "A new value"

importnb for Python and IPython

It is suggested to execute importnb-install to make sure that notebooks for each IPython session.

Restart and run all or it didn’t happen.

importnb excels in an interactive environment and if a notebook will Restart and Run All then it may reused as python code. The Notebook context manager will allow notebooks with valid names to import with Python.

>>> from importnb import Notebook

For brevity

[1]:
    with __import__('importnb').Notebook():
        import readme




```importnb.loader`` <src/notebooks/loader.ipynb>`__ will find notebooks available anywhere along the ```sys.path`` <https://docs.python.org/2/library/sys.html#sys.path>`__.

or explicity

[2]:
    from importnb import Notebook
    with Notebook():
        import readme
[3]:
    foo = 42
    with Notebook():
        import readme
    if __name__ == '__main__':
        assert readme.foo == 42
        assert readme.__file__.endswith('.ipynb')

Modules may be reloaded

The context manager is required to reload a module.

[4]:
    from importlib import reload
    with Notebook(): __name__ == '__main__' and reload(readme)

Lazy imports

The lazy option will delay the evaluation of a module until one of its attributes are accessed the first time.

[5]:
    with Notebook(lazy=True):
        import readme

Fuzzy File Names

[6]:
    if __name__ == '__main__':
        with Notebook():
            import __a_me

        assert __a_me.__file__ == readme.__file__

Python does not provide a way to import file names starting with numbers of contains special characters. importnb installs a fuzzy import logic to import files containing these edge cases.

import __2018__6_01_A_Blog_Post

will find the first file matching *2018*6?01?A?Blog?Post. Importing Untitled314519.ipynb could be supported with the query below.

import __314519

Docstring

The first markdown cell will become the module docstring.

[7]:
    if __name__ == '__main__':
        print(readme.__doc__.splitlines()[0])
__importnb__ imports notebooks as modules.  Notebooks are reusable as tests, source code, importable modules, and command line utilities.

Meaning non-code blocks can be executeb by `doctest <>`__.

[8]:
    if __name__ == '__main__':
        __import__('doctest').testmod(readme)

Import notebooks from files

Notebook names may not be valid Python paths. In this case, use Notebook.from_filename.

Notebook.from_filename('index.ipynb')

Import under the __main__ context.

Notebook('__main__').from_filename('index.ipynb')

Parameterize Notebooks

Literal ast statements are converted to notebooks parameters.

In readme, foo is a parameter because it may be evaluated with ast.literal_val

[9]:
    if __name__ == '__main__':
        from importnb.parameterize import Parameterize
        f = Parameterize.load(readme.__file__)

The parameterized module is a callable that evaluates with different literal statements.

[10]:
    if __name__ == '__main__':
        assert callable(f)
        f.__signature__

        assert f().foo == 42
        assert f(foo='importnb').foo == 'importnb'

Run Notebooks from the command line

Run any notebook from the command line with importnb. Any parameterized expressions are available as parameters on the command line.

!ipython -m importnb -- index.ipynb --foo "The new value"

IPython

IPython Extension

Avoid the use of the context manager using loading importnb as IPython extension.

%load_ext importnb

%unload_ext importnb will unload the extension.

Default Extension

importnb may allow notebooks to import by default with

!importnb-install






If you'd like to play with source code on binder then you must execute the command above. Toggle the markdown cell to a code cell and run it.

This extension will install a script into the default IPython profile startup that is called each time an IPython session is created.

Uninstall the extension with importnb-install.

Run a notebook as a module

When the default extension is loaded any notebook can be run from the command line. After the importnb extension is created notebooks can be execute from the command line.

ipython -m readme

In the command line context, __file__ == sys.arv[0] and __name__ == '__main__' .

Parameterizable IPython commands

Installing the IPython extension allows notebooks to be computed from the command. The notebooks are parameterizable from the command line.

ipython -m readme -- --help

importnb installs a pytest plugin when it is setup. Any notebook obeying the py.test discovery conventions can be used in to pytest. This is great because notebooks are generally your first test.

!ipython -m pytest -- src

Will find all the test notebooks and configurations as pytest would any Python file.

To package notebooks add recursive-include package_name *.ipynb

[11]:
    if __name__ == '__main__':
        if globals().get('__file__', None) == __import__('sys').argv[0]:
            print(foo, __import__('sys').argv)
        else:
            from subprocess import call
            !ipython -m pytest
            """Formatting"""
            from pathlib import Path
            from importnb.utils.export import export
            root = 'src/importnb/notebooks/'
            for path in Path(root).rglob("""*.ipynb"""):
                if 'checkpoint' not in str(path):
                    export(path, Path('src/importnb') / path.with_suffix('.py').relative_to(root))
            !jupyter nbconvert --to markdown --stdout index.ipynb > readme.md
/Users/tonyfast/anaconda3/lib/python3.7/site-packages/IPython/core/inputsplitter.py:22: DeprecationWarning: IPython.core.inputsplitter is deprecated since IPython 7 in favor of `IPython.core.inputtransformer2`
  DeprecationWarning)
]0;IPython: tonyfast/importnb============================= test session starts ==============================
platform darwin -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.13.0 -- /Users/tonyfast/anaconda3/bin/python
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/Users/tonyfast/importnb/.hypothesis/examples')
rootdir: /Users/tonyfast/importnb, inifile: tox.ini
plugins: hypothesis-4.36.2, nbval-0.9.2, black-0.3.7, pylint-0.14.1, xonsh-0.9.11, importnb-0.5.5
collected 19 items

src/importnb/completer.py::importnb.completer PASSED                     [  5%]
src/importnb/loader.py::importnb.loader.FinderContextManager PASSED      [ 10%]
src/importnb/utils/export.py::importnb.utils.export PASSED               [ 15%]
tests/test_importnb.ipynb::test_basic PASSED                             [ 21%]
tests/test_importnb.ipynb::test_package PASSED                           [ 26%]
tests/test_importnb.ipynb::test_reload PASSED                            [ 31%]
tests/test_importnb.ipynb::test_docstrings PASSED                        [ 36%]
tests/test_importnb.ipynb::test_docstring_opts PASSED                    [ 42%]
tests/test_importnb.ipynb::test_from_file PASSED                         [ 47%]
tests/test_importnb.ipynb::test_lazy PASSED                              [ 52%]
tests/test_importnb.ipynb::test_module_source PASSED                     [ 57%]
tests/test_importnb.ipynb::test_main PASSED                              [ 63%]
tests/test_importnb.ipynb::test_object_source PASSED                     [ 68%]
tests/test_importnb.ipynb::test_python_file PASSED                       [ 73%]
tests/test_importnb.ipynb::test_cli PASSED                               [ 78%]
tests/test_importnb.ipynb::test_parameterize PASSED                      [ 84%]
tests/test_importnb.ipynb::test_minified_json PASSED                     [ 89%]
tests/test_importnb.ipynb::test_fuzzy_finder PASSED                      [ 94%]
tests/test_importnb.ipynb::test_remote PASSED                            [100%]

=============================== warnings summary ===============================
src/importnb/completer.py::importnb.completer
src/importnb/completer.py::importnb.completer
src/importnb/completer.py::importnb.completer
src/importnb/completer.py::importnb.completer
  /Users/tonyfast/anaconda3/lib/python3.7/site-packages/IPython/core/completer.py:1950: PendingDeprecationWarning: `Completer.complete` is pending deprecation since IPython 6.0 and will be replaced by `Completer.completions`.
    PendingDeprecationWarning)

-- Docs: https://docs.pytest.org/en/latest/warnings.html
======================== 19 passed, 4 warnings in 2.93s ========================
[NbConvertApp] Converting notebook index.ipynb to markdown
[12]:
    if __name__ == '__main__':
        try:
            from IPython.display import display, Image
            from IPython.utils.capture import capture_output
            from IPython import get_ipython
            with capture_output():
                get_ipython().system("cd docs && pyreverse importnb -opng -pimportnb")
            display(Image(url='docs/classes_importnb.png', ))
        except: ...