export
Exporting a notebook to a library
ExportModuleProc
def ExportModuleProc():
A processor which exports code to a module
Specify lib_path where the module will be exported to, and optionally a class to use to create the module (ModuleMaker, by default).
Each notebook owns at most one module, named by #| default_exp. Exported cells are collected in cells, and cells included in __all__ in in_all.
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.cells[1].source
_bad = dict2nb({'cells': [mk_cell('#| default_exp a'), mk_cell('#| export b\nx = 1')]})
test_fail(lambda: NBProcessor(nb=_bad, procs=ExportModuleProc()).process(), contains='not supported', exc=ValueError)
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.cells],
[('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
nb_export
def nb_export(
nbname:str, # Filename of notebook
lib_path:str=None, # Path to destination library. Defaults to configured `lib_path`, else current directory.
procs=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 a fastship project.
):
Create a module from a 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 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
nb_mdoc
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('03_export.ipynb')
assert s.startswith('"""Exporting a notebook to a library')
s
ship_export
ship_export
def ship_export(
path:str=None, # Project root, notebook directory, or single notebook to export (default: configured project)
procs:str='', # Space-separated `module:name` processors to use (or set `export_procs` in config)
*, symlinks:bool=False, # Follow symlinks?
file_glob:str='*.ipynb', # Only include files matching glob
file_re:str=None, # Only include files matching regex
path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
path_re:str=None, # Only include files whose full paths match regex
folder_re:str=None, # Only enter folders matching regex
skip_file_glob:str=None, # Skip files matching glob
skip_file_re:str='^[_.]', # Skip files matching regex
skip_folder_re:str='^[_.]', # Skip folders matching regex
):
Export notebooks to Python modules and refresh tracked generated files (_modidx.py and generated README.md/CONTRIBUTING.md)