TIL: Pin dependencies with uv pip compile

Aug. 7, 2024 • TIL, Python

pip-compile is a command that takes a requirements.in file (listing top-level dependencies with optional version specifiers), and generates a requirements.txt with pinned versions of all dependencies.

This is great, because it allows you to maintain a much simpler requirements.in file, with just the top-level dependencies. The pinned versions in requirements.txt ensure consistent installs across different machines and over time. pip-compile automatically resolves conflicts between package versions, and therefore makes upgrading versions way easier.

This command is part of pip-tools, and it is also available with uv pip!

Quick start

Create a new virtual environment

uv venv
source .venv/bin/activate

Create a file requirements.in, listing your high level requirements.

# requirements.in

# Latest version of Django
django

# Or, with version constraints:
# Specify Django version 4.2 or higher, but not 5.0 or higher
django>=4.2,<5.0

# alternatively, this syntax also allows updates of patch versions
django~=4.2.0

Now run the command to compile a requirements.txt file.

uv pip compile requirements.in -o requirements.txt

It should look like this.

# requirements.txt

# This file was autogenerated by uv via the following command:
#    uv pip compile requirements.in -o requirements.txt
asgiref==3.8.1
    # via django
django==5.0.8
sqlparse==0.5.1
    # via django
typing-extensions==4.12.2
    # via asgiref

If you want to allow version upgrades, add the --upgrade flag.

uv pip compile requirements.in -o requirements.txt --upgrade

It is common to have dependencies for local development separate from prod dependencies. You can use the -c, --constraint flag to use the prod versions as a constraint. This ensures that versions match in both compiled requirement files.

uv pip compile requirements-dev.in -o requirements-dev.txt -c requirements.txt

The steps to upgrade, compile and install all dependencies then looks like this:

uv pip compile requirements.in -o requirements.txt --upgrade
uv pip compile requirements-dev.in -o requirements-dev.txt -c requirements.txt --upgrade

uv pip install -r requirements.txt
uv pip install -r requirements-dev.txt

May pinning and upgrading your production depencies be a breeze!


Recent posts