pyskills.ipynb

Functions for view/modifying ipynb file notebook cells. Each operation returns unified diffs showing what changed.
from fastcore.test import test_eq
_tmp = TemporaryDirectory()
_test_content = 'alpha\nbeta\ngamma\ndelta\n'

_nb_path = f'{_tmp.name}/test.ipynb'
_tnb = Notebook(new_nb([_test_content, 'other cell']))
_tnb.save(_nb_path)
_cid, _oid = _tnb[0].id, _tnb[1].id
def _nb_src(): return Notebook.open(_nb_path)[_cid].source
_cid, _oid
('fc4d7e8e', 'b0e7ba69')
res = cell_insert_line(_nb_path, _cid, 0, 'first')
test_eq(_nb_src().splitlines()[0], 'first')
print(res)
@@ -1 +1,2 @@
+first
 alpha
res = cell_str_replace(_nb_path, _cid, 'beta', 'BETA')
assert 'BETA' in _nb_src(), f"Expected 'BETA' in cell"
print(res)
@@ -2,3 +2,3 @@
 alpha
-beta
+BETA
 gamma
res = cell_strs_replace(_nb_path, _cid, ['gamma', 'delta'], ['GAMMA', 'DELTA'])
test_eq(_nb_src().splitlines()[-2:], ['GAMMA', 'DELTA'])
print(res)
@@ -3,3 +3,3 @@
 BETA
-gamma
-delta
+GAMMA
+DELTA
res = cell_replace_lines(_nb_path, _cid, 2, 3, 'two\nthree\n')
test_eq(_nb_src().splitlines()[1:3], ['two', 'three'])
print(res)
@@ -1,4 +1,4 @@
 first
-alpha
-BETA
+two
+three
 GAMMA
res = cell_del_lines(_nb_path, _cid, 1)
test_eq(_nb_src().splitlines()[0], 'two')
print(res)
@@ -1,2 +1 @@
-first
 two

source

view_cell


def view_cell(
    fname:str, id:str, nums:bool=True
):

Show cell source with optional line numbers

view_cell displays a cell’s source with line numbers, useful for checking content before editing:

print(view_cell(_nb_path, _cid))
     1 │ two
     2 │ three
     3 │ GAMMA
     4 │ DELTA

source

view_nb


def view_nb(
    fname:str, incl_out:bool=False
):

Show notebook source as concise xml, optionally including output if incl_out

view_nb(_nb_path)
'<nb path="test.ipynb"><code id="fc4d7e8e">two\nthree\nGAMMA\nDELTA</code><code id="b0e7ba69">other cell</code></nb>'