Skip to content

Commit 92c032e

Browse files
committed
fixes #25
1 parent 5dd7376 commit 92c032e

File tree

3 files changed

+119
-30
lines changed

3 files changed

+119
-30
lines changed

execnb/_modidx.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
'execnb.nbio.NbCell.parsed_': 'https://fastai.github.io/execnb/nbio.html#nbcell.parsed_',
4949
'execnb.nbio.NbCell.set_source': 'https://fastai.github.io/execnb/nbio.html#nbcell.set_source',
5050
'execnb.nbio.dict2nb': 'https://fastai.github.io/execnb/nbio.html#dict2nb',
51+
'execnb.nbio.mk_cell': 'https://fastai.github.io/execnb/nbio.html#mk_cell',
5152
'execnb.nbio.nb2dict': 'https://fastai.github.io/execnb/nbio.html#nb2dict',
5253
'execnb.nbio.nb2str': 'https://fastai.github.io/execnb/nbio.html#nb2str',
5354
'execnb.nbio.new_nb': 'https://fastai.github.io/execnb/nbio.html#new_nb',

execnb/nbio.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_nbio.ipynb.
22

33
# %% auto 0
4-
__all__ = ['NbCell', 'dict2nb', 'read_nb', 'nb2dict', 'nb2str', 'write_nb', 'new_nb']
4+
__all__ = ['NbCell', 'dict2nb', 'read_nb', 'new_nb', 'mk_cell', 'nb2dict', 'nb2str', 'write_nb']
55

66
# %% ../nbs/01_nbio.ipynb 2
77
from fastcore.imports import *
@@ -34,9 +34,9 @@ def __hash__(self): return hash(self.source) + hash(self.cell_type)
3434
def __eq__(self,o): return self.source==o.source and self.cell_type==o.cell_type
3535

3636
# %% ../nbs/01_nbio.ipynb 14
37-
def dict2nb(js):
37+
def dict2nb(js=None, **kwargs):
3838
"Convert dict `js` to an `AttrDict`, "
39-
nb = dict2obj(js)
39+
nb = dict2obj(js or kwargs)
4040
nb.cells = nb.cells.enumerate().starmap(NbCell)
4141
return nb
4242

@@ -48,25 +48,34 @@ def read_nb(path):
4848
return res
4949

5050
# %% ../nbs/01_nbio.ipynb 25
51+
def new_nb(cells=None, meta=None, nbformat=4, nbformat_minor=5):
52+
"Returns an empty new notebook"
53+
return dict2nb(cells=cells or [],metadata=meta or {},nbformat=nbformat,nbformat_minor=nbformat_minor)
54+
55+
# %% ../nbs/01_nbio.ipynb 27
56+
def mk_cell(text, # `source` attr in cell
57+
cell_type='code', # `cell_type` attr in cell
58+
**kwargs): # any other attrs to add to cell
59+
"Create an `NbCell` containing `text`"
60+
assert cell_type in {'code', 'markdown', 'raw'}
61+
if 'metadata' not in kwargs: kwargs['metadata']={}
62+
return NbCell(0, dict(cell_type=cell_type, source=text, directives_={}, **kwargs))
63+
64+
# %% ../nbs/01_nbio.ipynb 30
5165
def nb2dict(d, k=None):
5266
"Convert parsed notebook to `dict`"
53-
if k in ('source',): return d.splitlines(keepends=True)
67+
if k=='source': return d.splitlines(keepends=True)
5468
if isinstance(d, (L,list)): return list(L(d).map(nb2dict))
5569
if not isinstance(d, dict): return d
5670
return dict(**{k:nb2dict(v,k) for k,v in d.items() if k[-1] != '_'})
5771

58-
# %% ../nbs/01_nbio.ipynb 28
72+
# %% ../nbs/01_nbio.ipynb 33
5973
def nb2str(nb):
6074
"Convert `nb` to a `str`"
6175
if isinstance(nb, (AttrDict,L)): nb = nb2dict(nb)
6276
return dumps(nb, sort_keys=True, indent=1, ensure_ascii=False) + "\n"
6377

64-
# %% ../nbs/01_nbio.ipynb 31
78+
# %% ../nbs/01_nbio.ipynb 36
6579
def write_nb(nb, path):
6680
"Write `nb` to `path`"
6781
with maybe_open(path, 'w', encoding='utf-8') as f: f.write(nb2str(nb))
68-
69-
# %% ../nbs/01_nbio.ipynb 35
70-
def new_nb():
71-
"Returns an empty new notebook"
72-
return dict2nb({'cells':[],'metadata':{},'nbformat':4,'nbformat_minor':5})

nbs/01_nbio.ipynb

Lines changed: 98 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,9 @@
184184
"outputs": [],
185185
"source": [
186186
"#|export\n",
187-
"def dict2nb(js):\n",
187+
"def dict2nb(js=None, **kwargs):\n",
188188
" \"Convert dict `js` to an `AttrDict`, \"\n",
189-
" nb = dict2obj(js)\n",
189+
" nb = dict2obj(js or kwargs)\n",
190190
" nb.cells = nb.cells.enumerate().starmap(NbCell)\n",
191191
" return nb"
192192
]
@@ -250,7 +250,7 @@
250250
{
251251
"data": {
252252
"text/plain": [
253-
"([<ast.Expr at 0x107d476a0>], <ast.Add at 0x105235ee0>)"
253+
"([<ast.Expr at 0x1067c36a0>], <ast.Add at 0x1039bb2e0>)"
254254
]
255255
},
256256
"execution_count": null,
@@ -331,6 +331,83 @@
331331
"minimal.path_"
332332
]
333333
},
334+
{
335+
"cell_type": "markdown",
336+
"metadata": {},
337+
"source": [
338+
"# Creating a notebook"
339+
]
340+
},
341+
{
342+
"cell_type": "code",
343+
"execution_count": null,
344+
"metadata": {},
345+
"outputs": [],
346+
"source": [
347+
"#|export\n",
348+
"def new_nb(cells=None, meta=None, nbformat=4, nbformat_minor=5):\n",
349+
" \"Returns an empty new notebook\"\n",
350+
" return dict2nb(cells=cells or [],metadata=meta or {},nbformat=nbformat,nbformat_minor=nbformat_minor)"
351+
]
352+
},
353+
{
354+
"cell_type": "markdown",
355+
"metadata": {},
356+
"source": [
357+
"Use this function when creating a new notebook. Useful for when you don't want to create a notebook on disk first and then read it."
358+
]
359+
},
360+
{
361+
"cell_type": "code",
362+
"execution_count": null,
363+
"metadata": {},
364+
"outputs": [],
365+
"source": [
366+
"#| export\n",
367+
"def mk_cell(text, # `source` attr in cell\n",
368+
" cell_type='code', # `cell_type` attr in cell\n",
369+
" **kwargs): # any other attrs to add to cell\n",
370+
" \"Create an `NbCell` containing `text`\"\n",
371+
" assert cell_type in {'code', 'markdown', 'raw'}\n",
372+
" if 'metadata' not in kwargs: kwargs['metadata']={}\n",
373+
" return NbCell(0, dict(cell_type=cell_type, source=text, directives_={}, **kwargs))"
374+
]
375+
},
376+
{
377+
"cell_type": "code",
378+
"execution_count": null,
379+
"metadata": {},
380+
"outputs": [
381+
{
382+
"data": {
383+
"text/markdown": [
384+
"```json\n",
385+
"{ 'cell_type': 'code',\n",
386+
" 'directives_': {},\n",
387+
" 'execution_count': 0,\n",
388+
" 'idx_': 0,\n",
389+
" 'metadata': {},\n",
390+
" 'source': 'print(1)'}\n",
391+
"```"
392+
],
393+
"text/plain": [
394+
"{'cell_type': 'code',\n",
395+
" 'source': 'print(1)',\n",
396+
" 'directives_': {},\n",
397+
" 'execution_count': 0,\n",
398+
" 'metadata': {},\n",
399+
" 'idx_': 0}"
400+
]
401+
},
402+
"execution_count": null,
403+
"metadata": {},
404+
"output_type": "execute_result"
405+
}
406+
],
407+
"source": [
408+
"mk_cell('print(1)', execution_count=0)"
409+
]
410+
},
334411
{
335412
"cell_type": "markdown",
336413
"metadata": {},
@@ -347,7 +424,7 @@
347424
"#|export\n",
348425
"def nb2dict(d, k=None):\n",
349426
" \"Convert parsed notebook to `dict`\"\n",
350-
" if k in ('source',): return d.splitlines(keepends=True)\n",
427+
" if k=='source': return d.splitlines(keepends=True)\n",
351428
" if isinstance(d, (L,list)): return list(L(d).map(nb2dict))\n",
352429
" if not isinstance(d, dict): return d\n",
353430
" return dict(**{k:nb2dict(v,k) for k,v in d.items() if k[-1] != '_'})"
@@ -450,26 +527,29 @@
450527
"cell_type": "markdown",
451528
"metadata": {},
452529
"source": [
453-
"# Creating a notebook"
530+
"Here's how to put all the pieces of `execnb.nbio` together:"
454531
]
455532
},
456533
{
457534
"cell_type": "code",
458535
"execution_count": null,
459536
"metadata": {},
460-
"outputs": [],
461-
"source": [
462-
"#|export\n",
463-
"def new_nb():\n",
464-
" \"Returns an empty new notebook\"\n",
465-
" return dict2nb({'cells':[],'metadata':{},'nbformat':4,'nbformat_minor':5})"
466-
]
467-
},
468-
{
469-
"cell_type": "markdown",
470-
"metadata": {},
537+
"outputs": [
538+
{
539+
"name": "stdout",
540+
"output_type": "stream",
541+
"text": [
542+
"[{'cell_type': 'code', 'metadata': {}, 'source': 'print(1)', 'idx_': 0}]\n"
543+
]
544+
}
545+
],
471546
"source": [
472-
"Use this function when creating a new notebook. Useful for when you don't want to create a notebook on disk first and then read it."
547+
"nb = new_nb([mk_cell('print(1)')])\n",
548+
"path = Path('test.ipynb')\n",
549+
"write_nb(nb, path)\n",
550+
"nb2 = read_nb(path)\n",
551+
"print(nb2.cells)\n",
552+
"path.unlink()"
473553
]
474554
},
475555
{
@@ -486,8 +566,7 @@
486566
"outputs": [],
487567
"source": [
488568
"#|hide\n",
489-
"#|eval: false\n",
490-
"from nbdev.doclinks import nbdev_export\n",
569+
"from nbdev import nbdev_export\n",
491570
"nbdev_export()"
492571
]
493572
},

0 commit comments

Comments
 (0)