Skip to content

Commit 54d4850

Browse files
committed
add enable/disable cell number in .py files
1 parent a5a96be commit 54d4850

File tree

9 files changed

+41
-15
lines changed

9 files changed

+41
-15
lines changed

nbdev/config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ def _apply_defaults(
6666
jupyter_hooks:bool_arg=False, # Run Jupyter hooks?
6767
clean_ids:bool_arg=True, # Remove ids from plaintext reprs?
6868
clear_all:bool_arg=False, # Remove all cell metadata and cell outputs?
69+
cell_number:bool_arg=True, # Add cell number to the exported file
6970
put_version_in_init:bool_arg=True, # Add the version to the main __init__.py in nbdev_export
7071
):
7172
"Apply default settings where missing in `cfg`."
@@ -251,10 +252,10 @@ def add_init(path=None):
251252
if get_config().get('put_version_in_init', True): update_version(path)
252253

253254
# %% ../nbs/api/01_config.ipynb 51
254-
def write_cells(cells, hdr, file, offset=0):
255+
def write_cells(cells, hdr, file, offset=0, cell_number=True):
255256
"Write `cells` to `file` along with header `hdr` starting at index `offset` (mainly for nbdev internal use)."
256257
for cell in cells:
257-
if cell.source.strip(): file.write(f'\n\n{hdr} {cell.idx_+offset}\n{cell.source}')
258+
if cell.source.strip(): file.write(f'\n\n{hdr} {cell.idx_+offset if cell_number else ""}\n{cell.source}')
258259

259260
# %% ../nbs/api/01_config.ipynb 52
260261
def _basic_export_nb(fname, name, dest=None):

nbdev/doclinks.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,22 @@ def _iter_py_cells(p):
4747
"Yield cells from an exported Python file."
4848
p = Path(p)
4949
cells = p.read_text(encoding='utf-8').split("\n# %% ")
50+
has_cell_number = get_config().cell_number
5051
for cell in cells[1:]:
5152
top,code = cell.split('\n', 1)
5253
try:
53-
*nb,idx = top.split()
54-
nb = ' '.join(nb)
54+
if has_cell_number:
55+
*nb,idx = top.split()
56+
nb = ' '.join(nb)
57+
idx = int(idx)
58+
else:
59+
nb = top
60+
idx = None
5561
except ValueError: raise ValueError(f"Unexpected format in '{p}' at cell:\n```\n# %% {cell.strip()}.\n```\n"
5662
"The expected format is: '# %% {nb_path} {cell_idx}'.")
5763
nb_path = None if nb=='auto' else (p.parent/nb).resolve() # NB paths are stored relative to .py file
5864
if code.endswith('\n'): code=code[:-1]
59-
yield AttrDict(nb=nb, idx=int(idx), code=code, nb_path=nb_path, py_path=p.resolve())
65+
yield AttrDict(nb=nb, idx=idx, code=code, nb_path=nb_path, py_path=p.resolve())
6066

6167
# %% ../nbs/api/05_doclinks.ipynb 11
6268
def _nbpath2html(p): return p.with_name(re.sub(r'^\d+[a-zA-Z0-9]*_', '', p.name.lower())).with_suffix('.html')
@@ -71,7 +77,7 @@ def _get_modidx(py_path, code_root, nbs_path):
7177
_def_types = ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef
7278
d = {}
7379
for cell in _iter_py_cells(py_path):
74-
if cell.nb == 'auto': continue
80+
if 'auto' in cell.nb: continue
7581
loc = _nbpath2html(cell.nb_path.relative_to(nbs_path))
7682

7783
def _stor(nm):

nbdev/maker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def make(self:ModuleMaker, cells, all_cells=None, lib_path=None):
207207
f.write(f"# AUTOGENERATED! DO NOT EDIT! File to edit: {self.dest2nb}.")
208208
if last_future > 0: write_cells(cells[:last_future], self.hdr, f)
209209
if self.parse: f.write(f"\n\n# %% auto 0\n__all__ = {all_str}")
210-
write_cells(cells[last_future:], self.hdr, f)
210+
write_cells(cells[last_future:], self.hdr, f, cell_number=get_config().cell_number)
211211
f.write('\n')
212212

213213
# %% ../nbs/api/02_maker.ipynb 38

nbdev/sync.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ def nbdev_update(fname:str=None): # A Python file name to update
6767
if fname and fname.endswith('.ipynb'): raise ValueError("`nbdev_update` operates on .py files. If you wish to convert notebooks instead, see `nbdev_export`.")
6868
if os.environ.get('IN_TEST',0): return
6969
cfg = get_config()
70+
if not cfg.cell_number: raise ValueError("`nbdev_update` does not support without cell_number in .py files. Please check your settings.ini")
7071
fname = Path(fname or cfg.lib_path)
7172
lib_dir = cfg.lib_path.parent
7273
files = globtastic(fname, file_glob='*.py', skip_folder_re='^[_.]').filter(lambda x: str(Path(x).absolute().relative_to(lib_dir) in _mod_files()))

nbs/api/01_config.ipynb

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@
166166
" jupyter_hooks:bool_arg=False, # Run Jupyter hooks?\n",
167167
" clean_ids:bool_arg=True, # Remove ids from plaintext reprs?\n",
168168
" clear_all:bool_arg=False, # Remove all cell metadata and cell outputs?\n",
169+
" cell_number:bool_arg=True, # Add cell number to the exported file\n",
169170
" put_version_in_init:bool_arg=True, # Add the version to the main __init__.py in nbdev_export\n",
170171
"):\n",
171172
" \"Apply default settings where missing in `cfg`.\"\n",
@@ -209,7 +210,16 @@
209210
"cell_type": "code",
210211
"execution_count": null,
211212
"metadata": {},
212-
"outputs": [],
213+
"outputs": [
214+
{
215+
"name": "stderr",
216+
"output_type": "stream",
217+
"text": [
218+
"/home/dienhoa/miniconda3/envs/se/lib/python3.9/site-packages/ghapi/core.py:102: UserWarning: Neither GITHUB_TOKEN nor GITHUB_JWT_TOKEN found: running as unauthenticated\n",
219+
" else: warn('Neither GITHUB_TOKEN nor GITHUB_JWT_TOKEN found: running as unauthenticated')\n"
220+
]
221+
}
222+
],
213223
"source": [
214224
"#|hide\n",
215225
"if os.getenv('GITHUB_ACTIONS') != 'true': # GITHUB_TOKEN in actions has limited scope.\n",
@@ -742,10 +752,10 @@
742752
"outputs": [],
743753
"source": [
744754
"#|export\n",
745-
"def write_cells(cells, hdr, file, offset=0):\n",
755+
"def write_cells(cells, hdr, file, offset=0, cell_number=True):\n",
746756
" \"Write `cells` to `file` along with header `hdr` starting at index `offset` (mainly for nbdev internal use).\"\n",
747757
" for cell in cells:\n",
748-
" if cell.source.strip(): file.write(f'\\n\\n{hdr} {cell.idx_+offset}\\n{cell.source}')"
758+
" if cell.source.strip(): file.write(f'\\n\\n{hdr} {cell.idx_+offset if cell_number else \"\"}\\n{cell.source}')"
749759
]
750760
},
751761
{

nbs/api/02_maker.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@
519519
" f.write(f\"# AUTOGENERATED! DO NOT EDIT! File to edit: {self.dest2nb}.\")\n",
520520
" if last_future > 0: write_cells(cells[:last_future], self.hdr, f)\n",
521521
" if self.parse: f.write(f\"\\n\\n# %% auto 0\\n__all__ = {all_str}\")\n",
522-
" write_cells(cells[last_future:], self.hdr, f)\n",
522+
" write_cells(cells[last_future:], self.hdr, f, cell_number=get_config().cell_number)\n",
523523
" f.write('\\n')"
524524
]
525525
},

nbs/api/05_doclinks.ipynb

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,16 +135,22 @@
135135
" \"Yield cells from an exported Python file.\"\n",
136136
" p = Path(p)\n",
137137
" cells = p.read_text(encoding='utf-8').split(\"\\n# %% \")\n",
138+
" has_cell_number = get_config().cell_number\n",
138139
" for cell in cells[1:]:\n",
139140
" top,code = cell.split('\\n', 1)\n",
140141
" try:\n",
141-
" *nb,idx = top.split()\n",
142-
" nb = ' '.join(nb)\n",
142+
" if has_cell_number:\n",
143+
" *nb,idx = top.split()\n",
144+
" nb = ' '.join(nb)\n",
145+
" idx = int(idx)\n",
146+
" else:\n",
147+
" nb = top\n",
148+
" idx = None\n",
143149
" except ValueError: raise ValueError(f\"Unexpected format in '{p}' at cell:\\n```\\n# %% {cell.strip()}.\\n```\\n\"\n",
144150
" \"The expected format is: '# %% {nb_path} {cell_idx}'.\")\n",
145151
" nb_path = None if nb=='auto' else (p.parent/nb).resolve() # NB paths are stored relative to .py file\n",
146152
" if code.endswith('\\n'): code=code[:-1]\n",
147-
" yield AttrDict(nb=nb, idx=int(idx), code=code, nb_path=nb_path, py_path=p.resolve())"
153+
" yield AttrDict(nb=nb, idx=idx, code=code, nb_path=nb_path, py_path=p.resolve())"
148154
]
149155
},
150156
{
@@ -195,7 +201,7 @@
195201
" _def_types = ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef\n",
196202
" d = {}\n",
197203
" for cell in _iter_py_cells(py_path):\n",
198-
" if cell.nb == 'auto': continue\n",
204+
" if 'auto' in cell.nb: continue\n",
199205
" loc = _nbpath2html(cell.nb_path.relative_to(nbs_path))\n",
200206
"\n",
201207
" def _stor(nm):\n",

nbs/api/06_sync.ipynb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@
191191
" if fname and fname.endswith('.ipynb'): raise ValueError(\"`nbdev_update` operates on .py files. If you wish to convert notebooks instead, see `nbdev_export`.\")\n",
192192
" if os.environ.get('IN_TEST',0): return\n",
193193
" cfg = get_config()\n",
194+
" if not cfg.cell_number: raise ValueError(\"`nbdev_update` does not support without cell_number in .py files. Please check your settings.ini\")\n",
194195
" fname = Path(fname or cfg.lib_path)\n",
195196
" lib_dir = cfg.lib_path.parent\n",
196197
" files = globtastic(fname, file_glob='*.py', skip_folder_re='^[_.]').filter(lambda x: str(Path(x).absolute().relative_to(lib_dir) in _mod_files()))\n",

settings.ini

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,5 +66,6 @@ allowed_cell_metadata_keys =
6666
jupyter_hooks = True
6767
clean_ids = False
6868
clear_all = False
69+
cell_number = True
6970
put_version_in_init = True
7071

0 commit comments

Comments
 (0)