Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

Jupyter Workflows

Jupyter notebooks mix code, results, plots and narrative, ideal for exploration and communication, but their kernel keeps hidden state: cells can be run out of order, edited after running or deleted, so a notebook's outputs may not correspond to its code. This topic covers the notebook model (kernel, cells, execution counts, the .ipynb JSON format), productive habits (Restart & Run All, magics, autoreload, dependency order), version control (stripping outputs, jupytext), parameterized execution (papermill), and when to move code into modules and tests. In the exercises you manipulate notebook JSON (detect out-of-order and error cells, strip outputs, export to a script), then build an AST-based audit that predicts which notebooks will fail a clean re-run.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A lab notebook that runs

A Jupyter notebook is a document of cells: some hold code, some hold explanations, and code cells show their results (numbers, tables, plots) right underneath. Behind the page sits a kernel, a running Python session that remembers everything you’ve run. That memory is the catch: you can run cells in any order, change a cell after running it, or delete it, and the kernel still remembers the old values. The page can show results that its own code no longer produces.

Hidden state: the notebook says one thing, the kernel knows another
[ ]
temps = [21.0, 35.5, 48.2, 39.9, 51.3]
[ ]
limit = 45
[ ]
hot = [t for t in temps if t > limit]
[ ]
print(len(hot), "readings above limit")
kernel namespace: (empty)
Try: run A, B, C, D; then drag the limit and run only D: the printed count is stale. Or delete cell B after running it: everything still "works" until you press Restart & Run All. Notebook outputs are snapshots of a kernel's history, not of the code you see. Restart & Run All before sharing, keep cells in dependency order, and move real logic into tested modules.
Why engineers care

Notebooks are everywhere in data analysis, ML experiments and mission-operations quick looks, and they are a common source of irreproducible results. A study of a million GitHub notebooks found only about a quarter ran without errors and only a few percent reproduced their stored results (Pimentel et al., 2019). Disciplined notebook workflows make exploratory work reliable enough to base decisions on.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The kernel is…
  2. 2. After deleting a cell that defined x, x…
  3. 3. Before sharing a notebook you should…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The model

  • Cells: code, markdown or raw. [n] is the execution count, the n-th thing the kernel ran.
  • Kernel: a separate process (ipykernel for Python) talking to the front end (JupyterLab, VS Code, Colab) over ZeroMQ. You can interrupt or restart it.
  • The .ipynb file is JSON: a list of cells with source, outputs and execution_count, plus metadata.

Everyday tools

  • %timeit expr: benchmark. %%time: time a cell.
  • %load_ext autoreload and %autoreload 2: pick up edits in imported modules.
  • %matplotlib inline / widget: plotting backends.
  • !pip install x vs %pip install x: use %pip, which installs into the kernel’s environment.
  • ?obj / obj??: help and source.
📝 Quick check (Level 1)
0/3 answered
  1. 1. An .ipynb file is stored as…
  2. 2. To install a package into the current kernel's environment, use…
  3. 3. [7] next to a cell means…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

Habits that keep notebooks honest

  1. Top-to-bottom dependency order; restart and run all regularly, and always before sharing.
  2. Keep logic in modules (src/analysis.py) with tests; notebooks import and call them.
  3. Parameterize with a “parameters” cell and run headless with papermill for each test case or orbit.
  4. Pin the environment (C1.4) and record versions at the top (%load_ext watermark).
  5. Version control: strip outputs before committing (nbstripout) or pair the notebook with a plain script (jupytext .py:percent with # %% cell markers) for readable diffs.
  6. Seeds and data paths explicit at the top.
🐍 Exercise 1: notebooks are JSON
Work with an nbformat-4 notebook as a Python dict: list code cells, check whether execution counts increase from top to bottom and find out-of-order cells, find cells whose outputs contain errors, strip outputs and counts for version control (without modifying the original), and export to a '# %%' script.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Why strip outputs before committing?
  2. 2. papermill is used to…
  3. 3. jupytext pairs a notebook with…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Hidden state, formally

Let the notebook be cells c1,…,cnc_1, \dots, c_n (top to bottom) and the kernel history an execution sequence h=(ci1,ci2,… )h = (c_{i_1}, c_{i_2}, \dots), possibly including edited or deleted cells. The displayed outputs are a function of h, but a reader assumes they are a function of (c1,…,cn)(c_1, \dots, c_n) run in order. The two agree only if every name a cell reads was defined by an earlier cell in the top-to-bottom order, with the same code that ran.

A static check: walk the cells in order, tracking the set of defined names (assignments, imports, defs, plus builtins); report names used before definition. It can’t see dynamic tricks (exec, globals()[...], from x import *), so confirm with an actual clean run.

Beyond notebooks

Restart & Run All in CI (jupyter nbconvert --execute, pytest --nbmake) makes notebooks part of the test suite. Reactive notebooks (marimo, Pluto.jl) remove hidden state by re-running dependent cells automatically from the dependency graph.

📝 Quick check (Level 3)
0/3 answered
  1. 1. A static used-before-defined check can miss…
  2. 2. Reactive notebooks avoid hidden state by…
  3. 3. pytest --nbmake checks that…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Reproducibility, measured

Exercise 1. In the sample notebook, cells 4 and 5 have execution counts lower than the cell above (run out of order), and cell 5 stores a NameError output. Stripping outputs shrinks the JSON from 1039 to 889 bytes and leaves the original untouched; the script export has 7 # %% cells.

Exercise 2: a hidden-state audit. A 5-cell analysis computes a calibrated mean. The author’s real history, which included a since-deleted scale = 1.01 cell and ran the offset cell before the cell that uses it, printed 19.936. The AST audit flags cell 3 as using offset and scale before any cell defines them, and a clean top-to-bottom run indeed fails at cell 3 with a NameError. Restoring the deleted cell and moving the definitions above their use makes the clean run reproduce 19.936.

🐍 Exercise 2 (research): will this notebook survive Restart & Run All?
Using the ast module, find the names each cell defines and uses, report names used before any earlier cell defines them, then confirm by executing the cells in the author's recorded order and in a clean top-to-bottom order. Fix the notebook and show the clean run reproduces the author's result.

Notebooks in AI, robotics and aerospace

  • Exploratory data analysis of telemetry and test data, then promoted into tested modules.
  • ML experiment reports, executed by papermill for each configuration.
  • Mission-ops quick-look notebooks run in CI against new data drops.
  • Teaching and documentation that is guaranteed to execute.

References

  1. T. Kluyver et al. (2016). “Jupyter Notebooks: a publishing format for reproducible computational workflows.” Positioning and Power in Academic Publishing, IOS Press.
  2. J. F. Pimentel, L. Murta, V. Braganholo, J. Freire (2019). “A large-scale study about quality and reproducibility of Jupyter notebooks.” MSR.
  3. A. Rule et al. (2019). “Ten simple rules for writing and sharing computational analyses in Jupyter Notebooks.” PLOS Computational Biology, 15(7).
  4. nbformat documentation, The Notebook file format (nbformat.readthedocs.io).
  5. Project documentation: papermill, jupytext, nbstripout, nbmake, marimo.