Sub topic 3
Restart and run all before you trust a result
This chapter assumes you can write and run Python in a Jupyter notebook, use the command line, and have read the previous chapter on hidden state and execution order. You should know that a notebook kernel keeps variables in memory between cell runs, and that the order you ran cells in may differ from the order they appear on the page.
The goal here is a habit. Before you believe a number, a plot, or a table in a notebook, you restart the kernel and run every cell from top to bottom. If the notebook still produces the same result, the result depends only on what is written in the file. If it does not, you have found hidden state.
What the check does
A kernel is the process that runs your code and holds your variables. "Restart and run all" does two things in sequence:
- It kills the kernel and starts a new one, which discards every variable, import, and open file handle.
- It runs every code cell once, in the order the cells appear in the file.
After this, the kernel's memory is exactly what the notebook text can produce. Anything that worked only because of an earlier experiment, a deleted cell, or a cell run out of order is gone.
In JupyterLab, use the menu Kernel → Restart Kernel and Run All Cells. In classic Notebook, use Kernel → Restart & Run All. In VS Code, use Restart followed by Run All. The menu names differ, but the effect is the same.
What the check catches
Most failures fall into a few patterns. Knowing them makes the error messages easier to read.
| Symptom after restart | Likely cause | Typical fix |
|---|---|---|
| `NameError: name 'df_clean' is not defined` | A variable was created in a cell that was deleted, edited, or placed below its first use | Move or restore the cell that defines it |
| `ModuleNotFoundError` | A package was installed into the kernel by hand and is not recorded anywhere | Add it to the environment file (see the later chapter on pinning) |
| Different numbers than before | A cell was run twice, or a random generator was not seeded | Make each cell safe to run once; seed the generator |
| `FileNotFoundError` | Code relies on a file you created manually or a working directory that changed | Use project-relative paths and create the file in code |
| Cell runs but the plot looks wrong | A variable was modified in place by a cell that is now out of order | Rewrite so each step creates a new variable |
The silent failures are the dangerous ones. An error stops you. A changed number does not. That is why you compare outputs, not just check that nothing crashed.
A worked example
Consider a notebook with three cells. Suppose you ran them in the order 1, 3, 2, 3 while experimenting.
# Cell 1
import pandas as pd
df = pd.DataFrame({"x": [1, 2, 3, 4, 5]})# Cell 2
df["x"] = df["x"] * 10# Cell 3
print(df["x"].mean())The page order is 1, 2, 3. Cell 3 should print 30.0. But you ran cell 3, then cell 2, then cell 3 again. The first print gave 3.0 and the second gave 30.0. Now suppose you run cell 2 once more by accident. The values become 100, 200, and so on, and cell 3 prints 300.0. The cell is not idempotent: running it again changes the data.
A restart and run all gives 30.0 every time, because each cell runs exactly once. The check also exposes the weakness. If you must run a cell twice to get the right answer, the notebook is fragile. A safer version of cell 2 creates a new variable instead of overwriting the old one:
# Cell 2, rewritten
df_scaled = df.assign(x=df["x"] * 10)# Cell 3, rewritten
print(df_scaled["x"].mean())Now cell 2 can be run any number of times and always gives the same result.
Making the check a routine
A check you remember only sometimes will not protect you. Attach it to specific moments:
- Before you share a notebook or paste a result into a report.
- Before you commit a notebook to Git.
- After you delete or reorder cells, since those edits are the most common source of hidden dependencies.
- After you install or upgrade a package.
- At the end of a long session, before you close the laptop.
For long analyses, run the check on a schedule inside the work, not only at the end. If a notebook takes 40 minutes to run, you will skip it. In that case, split the slow steps out (the later chapters on modules and headless execution cover this) so the notebook itself runs quickly.
Running the check without clicking
Menus are fine for a quick look, but a command-line run is more reliable because it always starts a fresh kernel and always runs in file order. nbconvert can do this:
jupyter nbconvert --to notebook --execute analysis.ipynb --output analysis_executed.ipynbThe command reads analysis.ipynb, starts a new kernel, runs every cell in order, and saves the result as analysis_executed.ipynb. The original file is untouched. If any cell raises an error, the command stops and prints the traceback, and no executed copy is written.
Two details matter in practice:
- The working directory for the run is the directory you launch the command from, unless you configure otherwise. If your notebook reads
data/raw/measurements.csv, launch from the project root, or paths will break in the command-line run even though they worked in the browser. - By default
nbconvertstops at the first error. If you want the full list of failing cells, add--allow-errors. Use that for diagnosis only, because it saves a notebook that contains errors and looks finished.
Comparing results, not just exit codes
A clean run proves the notebook can complete. It does not prove the result is unchanged. To check the numbers, compare the key outputs before and after. A simple approach is to write the headline values to a small file and compare that file between runs.
import json
from pathlib import Path
results = {
"n_rows": 5,
"mean_x": 30.0,
}
out = Path("outputs")
out.mkdir(exist_ok=True)
(out / "summary.json").write_text(json.dumps(results, indent=2, sort_keys=True))Run the notebook twice from a fresh kernel and compare the files with diff:
jupyter nbconvert --to notebook --execute analysis.ipynb --output run1.ipynb
cp outputs/summary.json outputs/summary_run1.json
jupyter nbconvert --to notebook --execute analysis.ipynb --output run2.ipynb
diff outputs/summary_run1.json outputs/summary.json && echo "Results match"If diff prints nothing and the message appears, two independent runs agree. Floating-point values can differ in the last digits across machines, so for real analyses compare with a tolerance (for example math.isclose) rather than demanding identical text.
Reading what happened
The decision flow below shows how to interpret the outcome of a restart and run all.
Notice that the loop always returns to the restart. After any fix, the old result is void until a fresh run confirms it.
Limits of the check
Restart and run all is necessary but not sufficient. It tells you the notebook is self-consistent on this machine, today. It cannot detect:
- Environment drift. A different version of pandas on another machine can change results even when the notebook is perfectly ordered. Later chapters cover isolation and pinning.
- Changed input data. If the file on disk was edited, the notebook runs cleanly and gives different answers. The chapter on data provenance covers checksums.
- Unseeded randomness that happens to agree. Two runs can match by chance on a small sample. Seeding is the real fix, and a single matching pair of runs is weak evidence.
- Hidden dependence on the system. Environment variables, the current date, or files outside the project can all feed into a result without showing up as errors.
Treat a successful run as one piece of evidence. It rules out the most common hidden-state errors and costs only a few minutes.
Exercises
Exercise
A notebook cell uses a variable scores that you defined in a cell you deleted an hour ago. The notebook still runs fine when you press "Run All" in your open session. Why might it fail for a colleague, and what should you do?
Show answer
The open kernel still holds scores in memory from before the cell was deleted, so "Run All" without a restart finds it. A colleague's fresh kernel will raise a NameError. Use Restart Kernel and Run All Cells to reproduce the failure, then restore or rewrite the code that creates scores inside the notebook.
Exercise
Your notebook has a cell df["price"] = df["price"] * 1.1. After a restart and run all it gives the right total, but you notice it gave a different total last night. Name the likely cause and give a safer way to write the cell.
Show answer
The cell modifies df in place, so each extra run raises prices by another 10 percent, and last night's session probably ran it more than once. Write it to create a new variable, for example df_adj = df.assign(price=df["price"] * 1.1), so running it repeatedly always gives the same result.
Exercise
You run jupyter nbconvert --to notebook --execute analysis.ipynb and it fails with a FileNotFoundError for data/raw/measurements.csv, although the notebook works in your browser. What is a likely cause?
Show answer
The command was launched from a different directory than the project root, so the relative path data/raw/measurements.csv does not resolve. Run the command from the project root, or change the notebook to build paths relative to a known project directory.