export

Exporting a notebook to a library

source

ExportModuleProc

def ExportModuleProc(
    *args, **kwargs
):

A processor which exports code to a module

Specify dest where the module(s) will be exported to, and optionally a class to use to create the module (ModuleMaker, by default).

Exported cells are stored in a dict called modules, where the keys are the modules exported to. Those without an explicit module are stored in the '#' key, which will be exported to default_exp.

everything_fn = '../../tests/01_everything.ipynb'

exp = ExportModuleProc()
proc = NBProcessor(everything_fn, exp)
proc.process()
test_eq(exp.default_exp, 'everything')
assert 'print_function'  in exp.modules['#'][1].source
assert 'h_n' in exp.in_all['some.thing'][0].source

Markdown title cells and #| export markdown cells are collected into the module so ModuleMaker can build the module docstring. They must not be added to in_all, since __all__ generation only applies to Python symbols from code cells.

nb = dict2nb({'cells':[
    mk_cell('#| default_exp tmp_doc'),
    mk_cell('# Test module\n> Short summary', 'markdown'),
    mk_cell('#| export\nExtra docs', 'markdown'),
    mk_cell('#| exportd\nMore docs', 'markdown'),
    mk_cell('#| exportd\nprint(1)'),
    mk_cell('#| export\ndef f(): return 1')]})
exp = ExportModuleProc(); NBProcessor(nb=nb, procs=exp).process()
test_eq([(c.cell_type, c.source.splitlines()[0]) for c in exp.modules['#']], 
        [('markdown', '# Test module'), ('markdown', 'Extra docs'), ('markdown', 'More docs'),
         ('code', 'print(1)'), ('code', 'def f(): return 1')])
test_eq([c.cell_type for c in exp.in_all['#']], ['code'])
test_eq([c.source for c in exp.in_all['#']], ['def f(): return 1'])

nb_export


source

nb_export

def nb_export(
    nbname:str, # Filename of notebook
    lib_path:str=None, # Path to destination library.  If not in a nbdev project, defaults to current directory.
    procs:NoneType=None, # Processors to use
    name:str=None, # Name of python script {name}.py to create.
    mod_maker:type=ModuleMaker, debug:bool=False, # Debug mode
    solo_nb:bool=False, # Export single notebook outside of an nbdev project.
):

Create module(s) from notebook

Let’s check we can import a test file:

shutil.rmtree('tmp', ignore_errors=True)
nb_export('../../tests/00_some.thing.ipynb', 'tmp')

sys.path.append('')
g = exec_new('import tmp.some.thing')
sys.path.pop()
test_eq(g['tmp'].some.thing.__all__, ['a'])
test_eq(g['tmp'].some.thing.a, 1)
test_eq(g['tmp'].some.thing.__doc__, 
"Test module some.thing\n\nThis notebook is used to demonstrate exporting to an existing module. See the notebooks in `nbs` for how it's used.")

We’ll also check that our ‘everything’ file exports correctly:

nb_export(everything_fn, 'tmp')

g = exec_new('import tmp.everything; from tmp.everything import *')
_alls = L("a b d e m n o p q".split())
for s in _alls.map("{}_y"): assert s in g, s
for s in "c_y_nall _f_y_nall g_n h_n i_n j_n k_n l_n".split(): assert s not in g, s
for s in _alls.map("{}_y") + ["c_y_nall", "_f_y_nall"]: assert hasattr(g['tmp'].everything,s), s

That notebook should also export one extra function to tmp.some.thing:

del(sys.modules['tmp.some.thing']) # remove from module cache
g = exec_new('import tmp.some.thing')
test_eq(g['tmp'].some.thing.__all__, ['a','h_n'])
test_eq(g['tmp'].some.thing.h_n(), None)

nb_mdoc


source

nb_mdoc

def nb_mdoc(
    nbname:str, # Filename of notebook
):

The module docstring nb_export would write for nbname, for previewing while authoring

The module docstring is assembled from cells spread through the notebook, so it’s easy to end up with prose that reads well in the notebook but poorly in the projection (dangling colons, orphaned paragraphs). nb_mdoc shows the docstring nb_export would write, without exporting, for previewing while authoring:

s = nb_mdoc('04_export.ipynb')
assert s.startswith('"""Exporting a notebook to a library')
s
Path('../nbdev/export.py').unlink(missing_ok=True)
nb_export('04_export.ipynb')

g = exec_new('import nbdev.export')
assert hasattr(g['nbdev'].export, 'nb_export')