Sub topic 6
Pinning and recording dependencies
This chapter assumes you can create a virtual environment, install packages with pip, and run a Jupyter notebook. It builds on the previous chapter on isolating the environment. An isolated environment keeps projects apart. Pinning makes that environment recreatable later, on another machine, by another person.
Why an environment is not enough
A virtual environment is a folder of installed packages. It does not remember how it was built. If you delete it, or a colleague needs one, you must rebuild it from some written record. Without that record, pip install pandas installs whatever version is newest that day. Two installs a year apart can produce different environments and different numbers.
Version drift changes results in several ways:
- A function's default behavior changes between releases.
- A deprecated function is removed and the notebook fails.
- A numerical routine is reimplemented and results shift in the last digits.
- A dependency of a dependency changes, even though you never installed it directly.
Pinning means fixing each package to an exact version, so the install is the same every time.
Direct and transitive dependencies
A direct dependency is a package you import yourself, such as pandas. A transitive dependency is a package that your packages need, such as numpy or python-dateutil for pandas. Pinning only the direct ones leaves the rest free to drift, and they influence results too.
Freezing the environment
The simplest record is a frozen requirements file. The pip freeze command lists every installed package with its exact version, direct and transitive.
python -m venv .venv
source .venv/bin/activate
pip install pandas matplotlib
pip freeze > requirements.txt
# Later, on another machine:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtThe resulting file looks like this:
contourpy==1.3.0
cycler==0.12.1
matplotlib==3.9.2
numpy==2.1.1
pandas==2.2.3
python-dateutil==2.9.0.post0
pytz==2024.2
six==1.16.0The == operator requires that exact version. This is a pin.
Run pip freeze only inside the project's virtual environment. In a global environment it lists every package on the machine, including unrelated tools.
Two files: what you want and what you got
A frozen file has a drawback. It mixes the packages you chose with the ones pip pulled in, so you cannot tell which is which. Upgrading becomes hard because you do not know what is safe to remove.
A common approach is to keep two files:
| File | Contents | Written by |
|---|---|---|
| `requirements.in` | Direct dependencies, loosely constrained | You |
| `requirements.txt` | Every package, exact versions | A tool (`pip-compile` or `pip freeze`) |
The pip-tools package compiles the first into the second:
pip install pip-tools
pip-compile requirements.in --output-file requirements.txt
pip-sync requirements.txtpip-sync makes the environment match the file exactly, removing packages that are not listed. A plain pip install -r only adds, so stale packages can linger and hide a missing entry.
Hashes and version ranges
Exact pins fix the version number, but the file served for that number could in principle change. Adding hashes makes pip verify each download:
pip-compile --generate-hashes requirements.in --output-file requirements.txt
pip install --require-hashes -r requirements.txtThis is more protection than most analyses need. It matters when the environment is part of a security-sensitive pipeline.
Version ranges, such as pandas>=2.0,<3, belong in requirements.in or in a library's own metadata. They allow flexibility. A reproducible analysis needs the exact pin in the compiled file.
Python itself and non-Python dependencies
A requirements file records packages, not the interpreter. Results can change between Python 3.10 and 3.12. Record the Python version in at least one of these places:
- A
.python-versionfile, which tools such as pyenv read. - A note in the README.
- The run metadata described later in this tutorial.
Some packages also depend on system libraries, such as GDAL, a C compiler, or CUDA. Pip cannot pin these. If your analysis uses them, document them, or use conda, which can manage some of them. Conda has its own export command:
conda env export --from-history > environment.ymlThe --from-history flag lists only the packages you explicitly requested. Without it, the file contains platform-specific build strings that often fail on another operating system.
If the system-level dependencies are many or hard to describe, that is the point where a container becomes worth considering. A later chapter covers it.
Installing inside the notebook
Notebooks often contain a cell such as !pip install pandas. This is risky. It changes the environment while the kernel runs, it may install into a different Python than the kernel uses, and it leaves the install unpinned.
If you must install from a notebook, use the magic that targets the running kernel, and pin the version:
%pip install "pandas==2.2.3"A better practice is to install from requirements.txt before you open the notebook, and keep install commands out of the analysis cells.
Also make sure the notebook runs on the environment you think it does. Register the virtual environment as a Jupyter kernel:
pip install ipykernel
python -m ipykernel install --user --name my-analysis --display-name "Python (my-analysis)"If the notebook uses a different kernel than your .venv, your pins have no effect.
Recording versions in the notebook output
A requirements file describes what you intended to install. The notebook should also show what actually ran. Print the versions in a cell near the top, so they are saved in the output:
import platform
import sys
from importlib.metadata import version
print("Python:", sys.version)
print("Platform:", platform.platform())
for name in ["numpy", "pandas"]:
print(f"{name}:", version(name))If the printed versions differ from requirements.txt, you have a kernel mismatch or a stale environment. This check catches it.
Keeping pins current
Pins freeze the environment, which also freezes security fixes. Treat updates as a deliberate act:
- Change
requirements.inor runpip-compile --upgrade. - Rebuild the environment from the new file.
- Run the notebook from a clean kernel and compare results with the previous run.
- Commit the new
requirements.txttogether with any changed outputs.
Committing both together lets a later reader see which change in versions caused which change in results.
Common errors
- Freezing outside the venv. The file contains unrelated packages and may not install elsewhere.
- Pinning only direct dependencies. Transitive packages still drift.
- Not committing the file. An untracked
requirements.txtis not a record. Add it to Git. - Platform-specific pins. Wheels and build strings may differ between Linux, macOS, and Windows. Compile the file on the target platform, or use a tool that supports multiple platforms.
- Forgetting the interpreter version. The same pins on a different Python can give different results or fail to install.
- Mismatched kernel. The notebook runs on a Python that does not match the pinned environment.
Exercise
A colleague runs pip freeze > requirements.txt in the project's .venv and commits the file. A month later, a new teammate installs from it and gets different results from the same notebook, even though every package version matches. Name two things outside the requirements file that could explain the difference.
Show answer
The Python interpreter version may differ, since requirements.txt does not record it. System-level libraries (for example a C library that a package links against) may also differ. Other valid answers: the notebook is running on a different kernel than the venv, or the random seed and input data are not controlled, which earlier chapters cover.
Exercise
What is the difference between pip install -r requirements.txt and pip-sync requirements.txt, and why does it matter for reproducibility?
Show answer
pip install -r only installs or upgrades the listed packages, so extra packages already in the environment stay. pip-sync also removes packages that are not listed. With pip-sync, the environment matches the file exactly, so a missing entry cannot be hidden by a leftover package.