maker
Create one or more modules from selected notebook cells
ModuleMaker
def ModuleMaker(
dest, name, nb_path, parse:bool=True, solo_nb:bool=False
):
Helper class to create exported library from notebook source cells
In order to export a notebook, we need a way to create a Python file. ModuleMaker fills that role. Pass in the directory where you want the module created, the name of the module, and the path of the owning notebook. The location of the saved module will be in fname. Finally, if the source in the notebook should not be parsed by Python (such as partial class declarations in cells), parse should be set to False.
Note: If doing so, then the
__all__generation will be turned off as well.
mm = ModuleMaker(dest='tmp', name='test.testing', nb_path=Path.cwd()/'03_export.ipynb')
mm.fname
Path('tmp/test/testing.py')
ModuleMaker.make_all
def make_all(
cells
):
Create __all__ with all exports in cells
make_code_cells
def make_code_cells(
*ss
):
We want to add an __all__ to the top of the exported module. This methods autogenerates it from all code in cells.
nb = make_code_cells("from __future__ import print_function", "def a():...", "def b():...",
"c=d=1", "_f=1", "_g=1", "_h=1", "_all_=['_g', _h]", "@patch\ndef h(self:ca):...")
test_eq(set(mm.make_all(nb)), set(['a','b','c','d', '_g', '_h']))
relative_import
def relative_import(
name, fname, level:int=0
):
Convert a module name to a name relative to fname
test_eq(relative_import('nbdev.core', "xyz"), 'nbdev.core')
test_eq(relative_import('nbdev.core', 'nbdev'), '.core')
_p = Path('fastai')
test_eq(relative_import('fastai.core', _p/'vision'), '..core')
test_eq(relative_import('fastai.core', _p/'vision/transform'), '...core')
test_eq(relative_import('fastai.vision.transform', _p/'vision'), '.transform')
test_eq(relative_import('fastai.notebook.core', _p/'data'), '..notebook.core')
test_eq(relative_import('fastai.vision', _p/'vision'), '.')
test_eq(relative_import('fastai', _p), '.')
test_eq(relative_import('fastai', _p/'vision'), '..')
test_eq(relative_import('fastai', _p/'vision/transform'), '...')
NbCell.import2relative
def import2relative(
cell:fastcore.nbio.NbCell, libname
):
update_import
def update_import(
source, tree, libname, f:function=relative_import
):
ss = "from nbdev.export import *\nfrom nbdev.a.b import *"
cell = make_code_cells([ss])[0]
cell.import2relative('nbdev')
test_eq(cell.source, 'from .export import *\nfrom .a.b import *')
cell = make_code_cells([ss])[0]
cell.import2relative('nbdev/a')
test_eq(cell.source, 'from ..export import *\nfrom .b import *')
ModuleMaker.make
def make(
cells, all_cells=None, lib_path=None
):
Write module containing cells with __all__ generated from all_cells
cells = make_code_cells("from __future__ import print_function",
"#| export\ndef a(): ...", "def b(): ...")
mm.make(cells, L([cells[2]]))
src = Path('tmp/test/testing.py').read_text(encoding='utf-8')
assert '# AUTOGENERATED! DO NOT EDIT! File to edit:' in src and '\n# %% #' in src and '\n# %% ../' not in src
show_src(src)
# AUTOGENERATED! DO NOT EDIT! File to edit: ../../04_export.ipynb.
# %% ../../04_export.ipynb #bc0f5e48
from __future__ import print_function
# %% auto #0
__all__ = ['b']
# %% ../../04_export.ipynb #bacd036d
#| export
def a(): ...
# %% ../../04_export.ipynb #7812454e
def b(): ...
Pass all_cells=[] or parse=False if you don't want any __all__ added.
Passing parse=False is also handy for when writing broken up functions or classes that ast.parse might not like but still want it to be exported, such as having a cell with:
#| export
class A:
Note that by doing so we cannot properly generate a __all__, so we assume that it is unwanted.
am = ModuleMaker(dest='tmp', name='test.testing_noall', nb_path=Path.cwd()/'01_export.ipynb', parse=False)
am.fname
Path('tmp/test/testing_noall.py')
cells = make_code_cells("from __future__ import print_function", "#| export\ndef a(): ...", "#| export\nclass A:")
am.make(cells)
show_src(Path('tmp/test/testing_noall.py').read_text(encoding='utf-8'))
# AUTOGENERATED! DO NOT EDIT! File to edit: ../../01_export.ipynb.
# %% ../../01_export.ipynb #b102bbc6
from __future__ import print_function
# %% ../../01_export.ipynb #09e2fb00
#| export
def a(): ...
# %% ../../01_export.ipynb #d5e267cb
#| export
class A:
try:
sys.path.append('')
g = exec_import('tmp.test.testing', '*')
sys.path.pop()
assert 'b' in g
assert 'a' not in g
assert g['b']() is None
finally: shutil.rmtree('tmp')
scrub_magics
def scrub_magics(
cell
):
Remove Jupyter magic lines (e.g. %%time, %matplotlib) from exported code cells