Sub topic 1
What Reproducible Means and Why Notebooks Drift
Prerequisites
Assume you know basic Python, Jupyter, command-line use, Git, and package installation with pip or conda.
What Reproducible Means
A notebook analysis is reproducible when another person, or your future self, can use the documented code, data, software, and parameters to obtain the same result. Reproducibility includes the result and the process that produced it.
Notebooks often drift because they preserve more state than the visible file suggests:
- A cell may depend on a variable created by an earlier cell.
- Cells may be run out of order.
- Installed packages may change between runs.
- Input files may be replaced without notice.
- Random operations may produce different values.
- Outputs may remain visible even after the code that created them changes.
Hidden State and Execution Order
The kernel is the running Python process behind a notebook. It keeps variables, imports, and changed function definitions in memory. Running cell 5 before cell 2 can make a notebook appear to work even though a fresh reader cannot run it in order.
For example, this cell succeeds only if rate already exists:
total = 100 * rate
print(total)The notebook file does not explain where rate came from. A clean run exposes this dependency as an error.
The dependency flow should be explicit:
Restart and Run All Before You Trust a Result
Use the notebook interface's restart-and-run-all command before sharing a result. This clears the kernel and executes every cell from the beginning. Fix any error instead of running cells manually until the error disappears.
You can also execute a notebook in a fresh kernel from the command line:
jupyter nbconvert --to notebook --execute analysis.ipynb --output analysis_executed.ipynbKeep the executed copy as an artifact when you need evidence of the run. Repeat this check after changing cell order, inputs, or dependencies.
A Project Layout That Separates Code, Data, and Outputs
A predictable layout makes dependencies easier to inspect:
project/
├── notebooks/
├── src/
├── data/
│ ├── raw/
│ └── processed/
├── outputs/
├── requirements.txt
└── README.mdKeep reusable logic in src/, source files in data/raw/, derived files in data/processed/, and charts or reports in outputs/. The notebook should coordinate these pieces rather than hide the whole analysis in stateful cells.
Exercise
Why can a notebook show a correct chart even when running all cells from a fresh kernel fails?
Show answer
The chart may be a saved output from an earlier session, or the notebook may depend on variables created by out-of-order execution.