Sub topic 2
Creating lock files with pip-tools and uv
This chapter assumes you know basic pip usage, can run commands in a terminal, and have a Python project with a list of direct dependencies. You also need Docker for the last section.
Creating lock files with pip-tools and uv
A lock file lists every package your project installs, including indirect dependencies, at exact versions. You write the direct dependencies once, and a tool resolves them into a complete, pinned file.
With pip-tools, list the direct dependencies in requirements.in, then run:
pip install pip-tools
pip-compile --generate-hashes -o requirements.lock requirements.inWith uv, declare dependencies in pyproject.toml, then run:
uv lock
uv sync --lockeduv sync --locked fails if uv.lock no longer matches pyproject.toml, so it catches stale locks in CI.
Verifying packages with hashes
A hash is a fingerprint of a package file. The --generate-hashes flag writes the hash of each artifact into the lock file. Install with:
pip install --require-hashes -r requirements.lockpip refuses any package that is unpinned or whose hash does not match. A changed or tampered package therefore fails the install instead of installing silently.
What a lock file cannot pin
A lock file covers only Python packages. It does not pin:
- The Python interpreter version, such as 3.11.9 versus 3.12
- System libraries, such as glibc, OpenSSL or libgomp
- CUDA libraries and the GPU driver
A container can pin the first two. The driver stays on the host.
Containers and images in brief
A container is an isolated process started from an image. An image is a packaged file system that holds the operating system layer, system libraries and your code. A Dockerfile is a text recipe that builds an image. Each instruction creates a layer, and Docker caches layers it has already built.
A Dockerfile that installs from the lock file
FROM python:3.11-slim
WORKDIR /app
COPY requirements.lock .
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
COPY src/ ./src/
CMD ["python", "-m", "src.train"]Copy the lock file before the source code. The dependency layer then stays cached while you edit code. Build and run it with:
docker build -t ml-train:dev .
docker run --rm ml-train:devExercise
Why does uv sync --locked fail after you edit pyproject.toml without running uv lock?
Show answer
The lock file no longer matches the declared dependencies, so uv refuses to install from it.