Sub topic 8
Recording and recreating an environment with requirements.txt
This chapter assumes you can create and activate a virtual environment, install packages with python -m pip install, and read version specifiers such as >=2.31,<3. If any of those is unfamiliar, review the earlier chapters first.
A virtual environment lives in a directory you do not commit to version control. To share the project or rebuild it later, you need a text file that says what to install. In pip, that file is a requirements file, and by convention it is named requirements.txt.
What a requirements file is
A requirements file is a plain-text list of requirement specifiers, one per line. pip reads it when you pass -r:
python -m pip install -r requirements.txtEach line is the same kind of string you would type after pip install. The file adds a few conveniences:
- Lines starting with
#are comments. A#after whitespace on a line also starts a comment. - Blank lines are ignored.
- A trailing backslash continues a line onto the next one.
- A line such as
-r other.txtincludes another requirements file. - A line may carry an environment marker after a semicolon, so it applies only on some platforms or Python versions.
This is a small hand-written file:
# requirements.txt
requests>=2.31,<3
rich~=13.7
tomli>=2.0; python_version < "3.11"The first two lines use specifiers: any requests from 2.31 up to but not including 3, and any rich release compatible with 13.7 (>=13.7,<14). The third line installs tomli only on Python versions older than 3.11, because newer versions include TOML parsing in the standard library.
Two ways to produce the file
There are two approaches, and they answer different questions.
- Write it by hand. You list only the packages your project imports directly, with ranges you have chosen. The file states what the project needs.
- Generate it with
pip freeze. pip prints every installed package with its exact version. The file states what happened to be installed.
Each has a place:
| Property | Hand-written | Output of `pip freeze` |
|---|---|---|
| Contains dependencies of dependencies | No | Yes |
| Version style | Ranges, such as `>=2.31,<3` | Exact, such as `==2.32.3` |
| Readable as a statement of intent | Yes | Mostly no |
| Gives the same install next month | Not guaranteed | Very likely |
| Easy to update | Edit one line | Regenerate the whole file |
A hand-written file stays small and lets pip pick newer compatible releases. A frozen file is closer to a snapshot, which suits deployments, CI jobs, and bug reports where you need the same versions again.
Recording with pip freeze
Run pip freeze inside the active environment, and redirect the output to a file:
python -m pip freeze > requirements.txtThe output looks like this, with one name==version line for each installed distribution:
certifi==2024.8.30
charset-normalizer==3.4.0
idna==3.10
requests==2.32.3
urllib3==2.2.3Only requests was installed on purpose here. The other four arrived as its dependencies, and freeze lists them anyway. This is the main drawback of a frozen file. Six months later you cannot tell which lines you chose and which are leftovers.
What freeze leaves out or changes
- pip itself, setuptools, and wheel are omitted by default. Pass
--allto include them. Most projects leave them out because they belong to the environment, not the project. - Editable installs appear as a
-eline pointing at a path or a VCS URL. A path that exists on your machine will not exist on a colleague's. - Packages installed from a Git URL appear as a
name @ git+https://...reference rather than a version. - Packages you installed once and forgot appear too. Freeze reports the environment as it is, including experiments.
Before committing the output, open the file and read it.
A note for Windows PowerShell
In Windows PowerShell 5.1, the > operator writes UTF-16. Some tools that read the file handle that badly. To get UTF-8, write the file explicitly:
python -m pip freeze | Out-File -Encoding utf8 requirements.txtBe aware that this encoding can add a byte order mark at the start of the file. pip handles it, but other tools may not.
Recreating the environment
The point of the file is that a new environment can be built from it. Start with an empty environment, not an existing one:
python3 -m venv .venv-new
.venv-new/bin/python -m pip install -r requirements.txtThe second line calls the new environment's interpreter directly, so you do not need to activate anything. It also guarantees that the install lands in .venv-new and not in whatever environment happens to be active.
On Windows, the interpreter is at .venv-new\Scripts\python.exe.
pip resolves all requirements together before it installs anything. If two lines conflict, or a pinned version does not exist for your Python version, the command fails and usually installs nothing. That makes a failed rebuild easy to retry.
flowchart TD
A[Working environment] -->|pip freeze| B[requirements.txt]
B -->|commit| C[Version control]
C -->|checkout| D[Another machine or CI job]
D -->|python -m venv| E[Empty environment]
E -->|pip install -r| F[Rebuilt environment]
F -->|pip check and tests| G[Verified]The diagram above must use the required block form. Here it is again in that form:
Verifying the rebuild
A successful install does not prove the environment matches the original. Two checks help.
First, ask pip whether the installed set is consistent:
.venv-new/bin/python -m pip checkIt prints No broken requirements found. when every installed package's dependencies are present and compatible.
Second, compare the new environment with the file:
.venv-new/bin/python -m pip freeze > /tmp/rebuilt.txt
diff requirements.txt /tmp/rebuilt.txt && echo "identical"If the file came from pip freeze, the two should match. If you wrote the file by hand with ranges, differences are expected, because pip chose the newest releases that satisfy your ranges.
Splitting requirements by purpose
Projects often need packages that only developers use, such as a test runner. Keep them out of the runtime file by using a second file that includes the first:
# requirements-dev.txt
-r requirements.txt
pytest>=8,<9A deployment installs requirements.txt. A developer installs requirements-dev.txt, which pulls in everything from the first file and adds the test tools. Paths in -r lines are relative to the file that contains them, so keep related files in the same directory.
Edge cases and gotchas
Installing from a file does not remove anything. pip install -r adds and upgrades packages. If the environment already contains a package that is not in the file, it stays. For a faithful rebuild, use a fresh environment. You can remove a set of packages with python -m pip uninstall -r requirements.txt, but that removes only what the file names.
A frozen file is tied to a platform and Python version. Some packages ship different dependencies on different operating systems or Python versions. A file frozen on Linux with Python 3.12 may name a version that has no build for Windows or for Python 3.9. Environment markers help for lines you write yourself, but freeze does not add them. Freeze on the same kind of system where you will install.
Exact pins stop security updates. Pinning urllib3==2.2.3 keeps that version until someone changes the line. Plan a regular refresh: rebuild from the hand-written file in a clean environment, run the tests, then freeze again.
Duplicate and conflicting lines. Listing the same package twice with incompatible specifiers fails at resolution time with a conflict message. The fix is to edit the file so only one line names that package.
Local paths and editable installs. Do not commit -e /home/you/project. Use the editable install for your own project, as covered in a later chapter, and keep it out of the shared file.
Hash checking. Lines can carry --hash=sha256:... options, and pip then checks each downloaded file against them. If any line has a hash, pip requires hashes for every line and exact == pins. This protects against tampered or substituted packages, and it is usually produced by a tool rather than by hand.
A complete workflow
This sequence builds a project environment from a hand-written file, records a snapshot, and rebuilds from it:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python -m pip freeze > requirements.lock.txt
deactivate
python3 -m venv .venv-check
.venv-check/bin/python -m pip install -r requirements.lock.txt
.venv-check/bin/python -m pip checkThe two files serve different jobs. requirements.txt says what the project asks for. requirements.lock.txt records what that request produced on a given day. The next chapter shows how constraints files let you keep the first file short while still controlling the versions pip chooses.
Exercise
You run python -m pip install -r requirements.txt in an environment that already contains a package called flask, which is not listed in the file. Afterward, is flask still installed? What would you do to get an environment that contains exactly the file's packages and their dependencies?
Show answer
Yes, flask is still installed, because pip install -r only installs or upgrades what the file requires and never removes other packages. To get an exact match, create a new empty environment with python3 -m venv .venv-new and run .venv-new/bin/python -m pip install -r requirements.txt there.
Exercise
A colleague's requirements.txt, produced by pip freeze, contains the line -e /home/colleague/shop. Why does this break your install, and what should the file contain instead?
Show answer
The line is an editable install of a directory on the colleague's machine, and that path does not exist on yours, so pip fails. The shared file should leave out the editable line. Each developer installs their own copy of the local project with python -m pip install -e . from the project directory.
Exercise
Write a requirements-dev.txt that includes everything in requirements.txt and adds pytest at any 8.x release.
Show answer
The file needs two lines: -r requirements.txt and pytest>=8,<9.