Sub topic 3
Repeatable Installs with Constraints Files
This chapter assumes you can run shell commands, run Python scripts, and create a virtual environment. The examples use an active .venv.
Repeatable installs with constraints files
A requirements file declares what a project needs:
# requirements.txt
requestsA constraints file limits versions without adding new packages:
# constraints.txt
requests==2.32.3
urllib3<3Install the requirements while applying the constraints:
python -m pip install -r requirements.txt -c constraints.txtThe -c option tells pip which versions are allowed. A constraints file is useful when several projects share approved dependency versions.
Working on your own project with `pip install -e`
An editable install connects the environment to your project source:
python -m pip install -e .The project must provide packaging metadata, commonly in pyproject.toml. Changes to the source then take effect without reinstalling the project. This is convenient during development. It does not freeze dependencies, so keep the project’s requirements and constraints files under version control.
Rebuilding environments safely
Virtual environments are disposable. Add the environment directory to .gitignore:
.venv/
__pycache__/Do not commit installed files. Commit requirements.txt, constraints files, and project metadata instead. To rebuild, create a new environment and install from those files:
python3 -m venv .venv-new
.venv-new/bin/python -m pip install -r requirements.txt -c constraints.txtTroubleshooting common failures
- Check which interpreter and pip you are using:
python -c "import sys; print(sys.executable)"andpython -m pip --version. - If activation is missing, run the environment’s interpreter directly, such as
.venv/bin/python. - If an environment is corrupted, create a replacement and reinstall from the recorded files.
- Use
python -m pip, rather than barepip, to keep pip tied to that Python interpreter.
pip configuration and package indexes
pip can read configuration from user or system files. A private package index can be selected for one command:
python -m pip install --index-url https://packages.example.test/simple internal-libUse trusted, authenticated indexes and avoid putting credentials in shell history.
Where related tools fit
virtualenvis a third-party environment creator with broader historical compatibility.pipxinstalls command-line applications in separate environments.uvcombines fast environment and package-management workflows.
All three build on the same idea: keep project dependencies separate from the system Python installation.
Exercise
What does -c constraints.txt do when used with pip install -r requirements.txt?
Show answer
It limits the versions pip may choose for packages requested by the requirements file; it does not install packages by itself.