7 Reproducible Environments
7.1 The Problem This Solves
Six months after you finish a piece of analysis, someone asks you to rerun it. You clone your own repository, run the script, and it fails — a function that used to take three arguments now takes four, or a package you relied on has been renamed, or your machine has a newer Python than the one you wrote it on.
The same problem in its more embarrassing form: you send a colleague your code and it doesn’t run on their machine. Neither of you can tell why, because neither of you can see what’s different.
The cause in both cases is that your analysis had dependencies you never wrote down. The code was in Git. The environment the code needed was in your head, or nowhere.
An environment is the complete set of software your analysis depends on: the language version and the version of every package.
7.2 The Two Halves
Two things need to happen, and it’s worth separating them because different tools handle each:
- Isolation — each project gets its own set of packages, so installing something for project A can’t break project B.
- Recording — the exact contents of that set are written to a file, committed alongside the code, and can be reconstructed later or elsewhere.
You need both. Isolation alone protects you from today’s conflicts and not from next year’s, and a record of an environment you never isolated just documents a mess.
7.3 Choosing a Tool
There are four in common use for Python and one for R. The choice matters less than actually using one, but here is how they differ.
| Tool | Best when | Records to |
|---|---|---|
| venv | You want the standard library answer with nothing to install | requirements.txt |
| uv | Default choice for new Python projects — same model as venv, far quicker to resolve and install, manages Python versions too | requirements.txt or uv.lock |
| conda / Miniforge | You need packages with heavy compiled components — GDAL, CUDA-enabled PyTorch, many bioinformatics tools | environment.yml |
| pixi | You want conda’s package coverage with a lockfile and a modern CLI | pixi.lock |
| renv | R, always | renv.lock |
For a new Python project with ordinary data science dependencies, use uv. For anything that needs the conda ecosystem’s compiled packages, use Miniforge. For R, renv is the only real answer and it’s a good one.
Both give you conda. Anaconda’s Terms of Service restrict free use in organisations above a headcount threshold, which has caught out a number of companies who assumed it was free because the download was. Miniforge is community-maintained, defaults to the conda-forge channel, and carries no such restriction. If you already have Anaconda installed and you’re using it for personal work, it’s fine — but check the current terms before rolling it out at work.
7.4 Python: uv
uv is a single binary that replaces pip, venv, and pyenv. If you took the uv route in Python and R you already have it and can skip to the next block. Otherwise, install it once:
# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows (PowerShell)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Both download a script and run it straight away; The Command Line covers what that means and when to read the script first.
Then, in a project directory:
# Create an environment. uv downloads Python 3.13 if you don't have it.
uv venv --python 3.13Next, activate it. The command differs by platform — run only the one for yours.
# macOS / Linux
source .venv/bin/activate
# Git Bash on Windows
source .venv/Scripts/activate# Windows PowerShell
.venv\Scripts\Activate.ps1:: Windows cmd.exe
.venv\Scripts\activate.bat
A fresh Windows install refuses to run PowerShell scripts at all, so Activate.ps1 fails with cannot be loaded because running scripts is disabled on this system. This is not a problem with your environment. Allow locally-created scripts for your own user account, once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUserRemoteSigned permits scripts you wrote or that a tool generated locally, while still requiring a signature on anything downloaded from the internet. You need this once per machine, not per project.
With the environment active, install into it:
uv pip install pandas matplotlib scikit-learn jupyterThe .venv directory holds the environment. It should never be committed to Git — it’s large, machine-specific, and reconstructible from the record file. Add .venv/ to your .gitignore, a plain text file listing paths Git should leave alone; Editors and Version Control covers it properly and gives a template that already includes this line.
7.4.1 Recording It
uv pip freeze > requirements.txtThe > redirects the command’s output into a file instead of printing it to the screen. In Windows PowerShell 5.1, > writes the file as UTF-16, which Git stores as binary, so changes to it won’t show in a diff. Use this there instead:
uv pip freeze | Out-File -Encoding utf8 requirements.txtCommit requirements.txt. Anyone with it — including you, later — reconstructs the environment with:
uv venv --python 3.13
uv pip install -r requirements.txtrequirements.txt doesn’t record the Python version, so name it when you rebuild. The lockfile route in Lockfiles vs Loose Requirements records it for you.
7.5 Python: conda
If you need the conda ecosystem, the shape is the same:
# One environment per project, named after the project
conda create -n sales-forecast python=3.13
# Activate it
conda activate sales-forecast
# Install packages
conda install numpy pandas matplotlib scikit-learn jupyterThe naming matters more than it looks. The environment you created in Python and R — datasci under conda, or the .venv in your rbr-work folder under uv — is a reasonable scratchpad for working through this book, and it is exactly the pattern this chapter argues against for real work: one shared environment that several projects quietly depend on, so upgrading a package for one analysis breaks another. Give each project its own.
Activate it whenever you work on that project. Unlike venv/uv, conda environments live in a central location rather than in the project directory, so there’s nothing to .gitignore.
7.5.1 Recording It
conda env export --from-history > environment.yml--from-history writes only the packages you asked for, exactly as you asked for them. That keeps the file readable and portable. Without the flag, conda lists every package that came along as a dependency — transitive dependencies — each pinned to an exact build string, including builds that only exist for your operating system, and the file often won’t install on another platform.
The cost is that nothing is pinned unless you pinned it when you installed. Give versions at install time if you want them recorded:
conda install pandas=3.0 scikit-learn=1.9For an exact record of what’s installed, conda env export --no-builds > environment.yml pins every package’s version and drops the build strings, though it still lists packages that exist on only one operating system. Both commands end the file with a prefix: line giving the environment’s location on your machine. Delete it before you commit; it points at a folder that won’t exist on anyone else’s computer.
7.6 R: renv
renv gives each R project its own package library and a lockfile recording exactly what’s in it.
install.packages("renv")Then, from within your project (an RStudio Project, ideally):
# Set up renv for this project — creates a private library
renv::init()
# Install packages as normal
install.packages("ggplot2")
# ... then use them in your scripts, e.g. library(ggplot2) in analysis.R ...
# Record the current state
renv::snapshot()renv::snapshot() writes renv.lock, a JSON file — a plain text format of nested "key": value pairs, readable by both people and programs — listing the packages your project’s code uses, with each one’s version and where it came from. It finds them by scanning your scripts for library() calls and the like, so a package you’ve installed but haven’t used in a script yet isn’t recorded. renv::snapshot(type = "all") records everything in the project library instead. Commit renv.lock. The renv/library/ directory stays out of Git; renv::init() writes the .gitignore entries for you.
Anyone who clones the project runs:
renv::restore()and gets exactly your package versions.
packrat is not the answer
Older R material recommends packrat for this. Posit retired it in favour of renv years ago. If you meet a project using packrat, migrating is straightforward — renv::migrate() handles it.
7.7 Connecting the Environment to Your Tools
Creating an environment is half the job. Your editor and your notebooks each have their own idea of which Python to use, and neither picks up a new environment automatically. It’s a common reason people conclude that environments “don’t work”: the environment is fine, but the tool is still running a different one.
Jupyter notebooks. A notebook runs against a kernel, and your new environment is not one until you register it. From inside the activated environment:
# Install the machinery that lets Jupyter talk to this environment
uv pip install ipykernel # or: conda install ipykernel
# Register it under a name you'll recognise in the kernel menu
python -m ipykernel install --user --name sales-forecastThe environment now appears in Jupyter’s Kernel → Change kernel menu. If a notebook reports that pandas isn’t installed when you know it is, this is the usual cause — the notebook is running a kernel from a different environment.
VS Code. Run Python: Select Interpreter, as described in Editors and Version Control.
RStudio. renv::init() writes a .Rprofile into the project, so opening the RStudio Project activates the private library. The console prints a line confirming it on startup. Nothing further to configure — but this only works if you open the project rather than the individual .R file.
7.8 Lockfiles vs Loose Requirements
There’s a distinction worth understanding, because it determines how reproducible your record actually is.
A loose requirement says “pandas”. A pinned requirement says “pandas 3.0.5”. A lockfile says “pandas 3.0.5, and every package pandas itself depends on, at exactly these versions, with a checksum for each — a short fingerprint computed from the file’s contents, which won’t match if the file has been altered or replaced.”
requirements.txt from pip freeze sits in the middle: it pins direct and transitive dependencies to versions, but not to checksums, and it doesn’t distinguish between what you asked for and what came along. renv.lock, uv.lock, and pixi.lock are true lockfiles.
For most analysis work, a pinned requirements.txt is enough. Prefer a real lockfile for anything whose result someone will act on months later.
7.8.1 A Lockfile with uv
uv writes one when you manage the folder as a project instead of a bare environment. In a new project folder:
uv init --bare # writes pyproject.toml
uv python pin 3.13 # writes .python-version
uv add pandas matplotlib # adds them to pyproject.toml, writes uv.lock, creates .venvCommit pyproject.toml, .python-version and uv.lock. Someone who clones the project runs uv sync, which builds .venv from the lockfile on the pinned Python version, and uv run python analysis.py runs a script in that environment without activating anything. From then on, add packages with uv add instead of uv pip install, so the lockfile stays current.
7.9 What Goes in Git
| Commit | Never commit |
|---|---|
requirements.txt / environment.yml / renv.lock / uv.lock |
.venv/, venv/, env/ |
.python-version |
renv/library/ |
pyproject.toml |
__pycache__/, .Rhistory, .RData |
The rule underneath is that you commit the description of the environment, never the environment itself.
7.10 Making It a Habit
The usual failure mode is drift: you set up an environment, then install three more packages over the following weeks without re-recording. Two things prevent it:
- Re-record when you add a package. Run
uv pip freeze > requirements.txtstraight after installing, or useuv add, which updates the lockfile itself. With renv, runrenv::snapshot()once your code uses the new package. - Let CI catch you. A continuous integration workflow (covered in Optimising Workflows) builds your project from nothing but the record file. If you forgot to record something, the build fails — in front of you, on a commit, rather than in front of a colleague six months later. For analysis work this is most of CI’s value.
7.11 Environments and Containers
A reasonable question at this point: if containers (covered in Containerisation) also make things reproducible, why bother with both?
They solve overlapping but different problems. An environment file pins your packages. A container pins the packages and the operating system, the system libraries, the locale, and the compiler toolchain. That extra coverage matters when a package depends on a specific version of a C library, or when the analysis has to run on infrastructure you don’t control.
Use an environment file always; it costs nothing. Reach for a container when the environment file isn’t enough — deployment, awkward system dependencies, or a colleague on a different platform. The two compose: a good container is usually a base image plus your requirements.txt.
7.12 Conclusion
By the end of this chapter you should have:
- Every active project in its own isolated environment
- A
requirements.txt,uv.lock,environment.yml, orrenv.lockcommitted alongside the code .venv/andrenv/library/in your.gitignore- Your editor pointed at the right interpreter, and the environment registered as a Jupyter kernel if you use notebooks
- Successfully reconstructed one of your own environments from its record file — do this once deliberately, so you find out now whether the file is actually complete
With environments recorded, the foundations are done. The next section turns to producing output someone else can read.