Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/internal/add_try_except_in_probml_utils_line.py
1191 views
1
import pytest
2
from glob import glob
3
import nbformat
4
5
# Load notebooks
6
notebooks1 = glob("notebooks/book1/*/*.ipynb")
7
notebooks2 = glob("notebooks/book2/*/*.ipynb")
8
notebooks = notebooks1 + notebooks2
9
10
11
def get_try_except_probml_utils_line(line):
12
f"""
13
check if import probml_utils is in given line: {line}
14
if present, then return {line} wrapped with try...except
15
"""
16
line = line.rstrip()
17
if not line.startswith(" ") and "probml_utils" in line and "import" in line:
18
try_except_line = (
19
f"try:\n {line}\nexcept ModuleNotFoundError:\n %pip install git+https://github.com/probml/probml-utils.git\n {line}"
20
)
21
return try_except_line
22
return 0
23
24
25
# Parameterize notebooks
26
@pytest.mark.parametrize("notebook", notebooks)
27
def add_try_except_for_probml_util(notebook):
28
nb = nbformat.read(notebook, as_version=4)
29
for cell in nb.cells:
30
lines = cell["source"].split("\n")
31
for line_no, line in enumerate(lines):
32
updated_line = get_try_except_probml_utils_line(line)
33
if updated_line:
34
lines[line_no] = updated_line
35
break
36
cell["source"] = "\n".join(lines)
37
nbformat.write(nb, notebook)
38
39
40
if __name__ == "__main__":
41
for notebook in notebooks:
42
add_try_except_for_probml_util(notebook)
43
44