Sub topic 11
Make the notebook reproducible by recording dependencies
This chapter assumes you can create and activate a virtual environment, install packages with pip, and run cells in JupyterLab. You should also know what a kernel is and how to restart one. The goal is to let another person (or you, six months from now) rebuild the environment your notebook ran in and get the same results.
What reproducible means here
A notebook is reproducible when someone else can take your files, recreate the software environment, run the cells in order, and get the same outputs. Three things have to be fixed for that to work:
- The code and its execution order.
- The input data.
- The package versions, plus the Python version.
Earlier chapters covered execution order and hidden state. This chapter covers the third item. Without recorded versions, a notebook that works today can break after a library update. A typical example is a pandas release that removes a deprecated argument your code relies on.
Freeze the installed packages
With your project environment active, write every installed package and its exact version to a file:
python -m pip freeze > requirements.txtSomeone else recreates the environment like this:
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txtUsing python -m pip makes sure the pip that runs belongs to the Python you intend. A bare pip on your path may belong to a different installation.
The output of pip freeze looks like this, though the exact packages and numbers depend on your machine:
jupyterlab==4.2.5
matplotlib==3.9.2
numpy==2.1.1
pandas==2.2.3The file lists many more lines than that. JupyterLab pulls in dozens of dependencies, and freeze records all of them.
Direct versus transitive dependencies
A direct dependency is a package you chose to install, such as pandas. A transitive dependency is a package that one of your choices needs, such as numpy for pandas. pip freeze lists both without telling you which is which.
This has trade-offs.
| Approach | Strength | Weakness |
|---|---|---|
| Full `pip freeze` output | Rebuilds nearly the same environment | Hard to read, and hard to tell what you actually chose |
| Hand-written file of direct dependencies | Short and readable | Transitive versions can drift between installs |
| Both: a short input file plus a frozen output file | Readable and exact | Two files to maintain |
A common compromise is to keep a short requirements.in that lists only what you chose, and treat requirements.txt as the generated, exact result.
jupyterlab
pandas
matplotlibYou can pin loosely when the exact version does not matter, and tightly when it does:
pandas>=2.2,<3
matplotlib==3.9.2The >=2.2,<3 form accepts any 2.x release from 2.2 on. The == form accepts exactly one version.
Record the Python version too
Package versions depend on the Python version. A package pinned in requirements.txt may not exist for an older or newer Python. Note the version somewhere visible. You can print it from inside the notebook so it travels with the outputs:
import sys
import pandas as pd
import matplotlib
print("Python :", sys.version.split()[0])
print("pandas :", pd.__version__)
print("matplotlib:", matplotlib.__version__)Put this in the first or last cell. When someone reports that your notebook behaves differently, this output is the first thing to compare.
You can also write the Python version in a short README.md next to the notebook:
Python 3.12
Create the environment with: python -m venv .venv
Install with: python -m pip install -r requirements.txtConfirm the file actually works
A requirements file you have never used to build an environment is an unverified claim. Test it in a fresh environment:
python -m venv .venv-test
source .venv-test/bin/activate # Windows: .venv-test\Scripts\activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip checkpip check reports installed packages that have missing or incompatible dependencies. No output besides "No broken requirements found." means the set is consistent. After this, register the test environment as a kernel or run the notebook with nbconvert against it, and confirm the results match. Delete .venv-test when you are done.
The whole workflow
The diagram shows how the pieces connect. You build and verify the environment, then run the notebook from a clean state.
Run all cells from a clean kernel
Reproducibility also depends on execution order. In JupyterLab, choose Kernel > Restart Kernel and Run All Cells. If any cell fails, or an output differs from what you saw before, the notebook relied on hidden state. A variable defined in a cell you later deleted is a common cause.
You can do the same check from the terminal, without opening the interface:
jupyter nbconvert --to notebook --execute --inplace analysis.ipynbThis runs every cell in order in a new kernel and saves the outputs. A failing cell stops the run with an error, which makes the command usable in an automated check.
If the notebook needs a specific kernel, name it:
jupyter nbconvert --to notebook --execute --inplace \
--ExecutePreprocessor.kernel_name=data-analysis analysis.ipynbThe kernel name data-analysis matches the one registered earlier with ipykernel install.
Remove other sources of nondeterminism
Matching packages do not guarantee matching results. Check these:
- Random numbers. Set a seed so random sampling repeats. With NumPy, create a generator with a fixed seed:
import numpy as np
rng = np.random.default_rng(seed=42)
sample = rng.normal(size=5)
print(sample)- Paths. Use relative paths such as
data/sales.csv, notC:\Users\you\Desktop\sales.csv. Absolute paths fail on every other machine. - Input data. If the CSV changes, results change. Keep the file in the project, or record where it came from and when you downloaded it.
- Current time. Code that calls
datetime.now()gives a different answer on each run. Pass dates in explicitly where you can. - Row order. Some operations, such as reading from a database without
ORDER BY, return rows in no guaranteed order. Sort explicitly before you rely on position.
Common errors
- Installing with
pipoutside the environment. The package lands in the wrong Python, andrequirements.txtmisses it. Check withpython -c "import sys; print(sys.prefix)"that the path points inside.venv. - A package installed in the terminal but not visible in the notebook. The notebook kernel uses a different Python. Select the registered kernel and confirm with
sys.executable. - Freezing too early. You add a package after freezing and forget to freeze again. Regenerate the file whenever you install something.
- Platform-specific pins. A frozen file from Windows may include packages that do not exist on Linux or macOS. For cross-platform projects, prefer the short input file and let
pipresolve versions per platform. - Editable or local installs. Lines such as
-e git+...orfile:///...in the frozen output point to places other people cannot reach. Review the file before sharing it.
You can check the interpreter a notebook is using with one cell:
import sys
print(sys.executable)The printed path should end inside your project's .venv.
Where this fits
Recording dependencies is the base for the next two topics. Version control stores the notebook and requirements.txt together so that each commit pairs code with the environment it needs. Exporting with nbconvert then gives you a way to run and share the notebook reliably. Commit requirements.txt with every change that adds or upgrades a package, so the history shows when versions moved.
Exercise
You freeze your environment and send requirements.txt plus analysis.ipynb to a colleague. They rebuild the environment, run all cells, and get a ModuleNotFoundError for seaborn, which your notebook imports. What most likely went wrong, and how do you prevent it?
Show answer
You most likely installed seaborn after running pip freeze, or installed it with a pip outside the project environment, so it never appeared in requirements.txt. Activate .venv, confirm with sys.executable that the notebook kernel uses it, install seaborn with python -m pip install seaborn, and regenerate the file with python -m pip freeze > requirements.txt. Then verify by building a fresh environment from the file and using Restart Kernel and Run All Cells.
Exercise
Name two reasons a notebook can give different results on another machine even when every package version matches.
Show answer
Any two of these: no random seed is set, absolute file paths differ, the input data changed, the code depends on the current time, rows come back in an unspecified order, or the Python version differs. Hidden state from out-of-order cell execution is another valid answer.