Skip to content

Lesson 2 of 59Your Python toolbox

uv for Real Projects

Run a whole project with uv, from Python versions and dependency groups to lockfiles, CI, Docker, single-file scripts and migrating from pip.

16 min read0/4 questions

You already know the basic uv commands, uv init, uv add and uv run, from Virtual Environments in the Python course. On a real team, the questions get harder. Why did CI install a different version than your laptop? Should uv.lock be committed, and what happens when two people change it at once? How do you share a one-file script that needs httpx without a whole project? And how do you move a five-year-old repo off requirements.txt? This lesson treats uv as what it is: one tool that owns your Python version, your environment, your dependencies and your lockfile, and shows how those pieces fit together.

One tool, five old jobs

Before uv, a Python project needed a stack of tools that each did one part of the job. uv replaces all of them with one binary and one mental model.

JobThe old wayuv
Install Python versionspyenv, the python.org installeruv python install, uv python pin
Create environmentspython -m venv, virtualenvAutomatic (.venv), or uv venv
Declare and install dependenciespip, requirements.txtuv add, uv remove
Lock exact versionspip-tools, Poetryuv lock (automatic)
Run global CLI toolspipxuv tool install, uvx

The important idea is that uv treats these as one system. When you run uv run pytest, uv checks that the right Python is available, that .venv exists, that uv.lock matches pyproject.toml, and that .venv matches uv.lock. It fixes whatever is out of date, then runs the command. You stop thinking about "did I activate the venv" or "did I reinstall after pulling".

How uv keeps a project in sync
pyproject.toml: what you wantpyproject.tomlwhat you wantuv.lock: exact resolutionuv.lockexact resolution.venv: what is installed.venvwhat is installed.python-version: which Python.python-versionwhich Pythonuv run: your commanduv runyour commanduv lockuv syncinterpreterruns inside

pyproject.toml holds your intent: direct dependencies with loose ranges like fastapi>=0.115. You edit it, usually through uv add.

1/4

Python versions

uv can download and manage Python itself, so you never need a system-wide install to start a project.

uv python install 3.13       # download a managed CPythonuv python pin 3.13           # write .python-version in this folderuv python list               # what is installed and available

Two settings work together here. requires-python = ">=3.12" in pyproject.toml says which versions your project supports, and uv uses it when resolving: it will not pick a package version that drops support for a Python you claim to support. .python-version says which version this checkout uses for its .venv. Commit both. When a teammate runs uv sync, uv downloads 3.13 if they do not have it.

pyproject.toml anatomy

Here is a realistic FastAPI service file:

pyproject.toml
[project]
name = "todo-api"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "fastapi[standard]>=0.115",
    "sqlalchemy>=2.0",
    "pydantic-settings>=2.6",
    "psycopg[binary]>=3.2",
]
 
[dependency-groups]
dev = ["pytest>=8.3", "pytest-cov>=6.0", "ruff>=0.9", "mypy>=1.14"]
docs = ["mkdocs-material>=9.5"]
  • [project] dependencies are what the app needs to run in production. uv add httpx writes here, with a lower bound on the version it just installed.
  • [dependency-groups] are for development only. uv add --dev pytest writes to the dev group, and uv add --group docs mkdocs-material creates any group you like. They are never installed for users of a published package.
  • Extras like fastapi[standard] are optional feature sets a package offers. [standard] pulls in Uvicorn, the fastapi CLI and other common pieces.

uv sync installs your dependencies plus the dev group by default. uv sync --no-dev leaves dev tools out (what you want in a production image), --group docs adds another group, and --all-groups installs everything.

Removing is just as easy: uv remove httpx deletes it from pyproject.toml, re-locks, and uninstalls it along with anything only it needed. uv tree prints the full dependency tree, which answers "why is this package even installed?"

Quick check
You run uv add --dev pytest. Where does pytest end up?
Need a nudge? A hint rules out a wrong answer.

uv.lock and reproducible installs

uv.lock records the exact version, source URL and hash of every package in the resolution. Three properties make it more useful than a pip freeze file:

  1. It is universal. uv resolves for every platform and supported Python at once. Open a lockfile made on a Mac and you will see packages like colorama that only Windows needs, with markers saying when they apply. One file works on macOS laptops, Windows laptops and Linux CI.
  2. It has hashes. If a package file on the index ever changed, the install would fail instead of silently running different code.
  3. It is generated, never edited. Change pyproject.toml (or run uv add), and uv updates the lock.

Commit it, always, for applications. If two branches both change dependencies and git reports a conflict in uv.lock, do not hand-merge it: take either side, then run uv lock to regenerate it from the merged pyproject.toml.

Upgrades are explicit. uv lock --upgrade-package sqlalchemy moves one package to the newest version your ranges allow. uv lock --upgrade moves everything. Do these in their own pull request, so if something breaks you know why.

Two flags matter in automation, and they are easy to mix up:

FlagMeaningUse it when
--lockedFail if uv.lock is out of date with pyproject.tomlCI: catch someone who edited pyproject.toml but did not commit the new lock
--frozenUse uv.lock as it is, without checking it against pyproject.tomlDocker builds, where only the lock may be copied in yet
Match the pairs0/5 matched

Match each command to its job.

Choose an item, then its match on the other side.

uv in CI and Docker

In GitHub Actions, the official astral-sh/setup-uv action installs uv and can cache downloaded packages between runs. After checkout, the job runs uv sync --locked, then your checks with uv run:

.github/workflows/ci.yml (the steps)
steps:
  - uses: actions/checkout@v4
  - uses: astral-sh/setup-uv@v6
    with:
      enable-cache: true
  - run: uv sync --locked
  - run: uv run ruff check .
  - run: uv run pytest

Pin the action to a release you have checked; the CI/CD lesson later builds the full workflow. In a Dockerfile (built in full in the deploying lesson) the pattern is: copy pyproject.toml and uv.lock first, run uv sync --frozen --no-dev --no-install-project so the dependency layer is cached, then copy your code and sync again. Both rely on the same promise: the lockfile is the single source of truth, so your laptop, CI and production all install identical packages.

Put it in order5 steps

Order the steps of a CI job for a uv project.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Single-file scripts with inline metadata

Not everything deserves a project. For a one-file script, say a data export or a quick API check, Python has a standard (PEP 723) for writing dependencies inside the file, in a special comment block. uv add --script writes it for you:

export_users.py
# /// script
# requires-python = ">=3.12"
# dependencies = [
#     "httpx>=0.28",
#     "rich>=13.9",
# ]
# ///
import httpx
from rich import print
 
users = httpx.get("https://api.example.com/users", timeout=10).json()
print(users[:3])

uv run export_users.py reads the block, builds a cached, throwaway environment with those packages, and runs the script. Send the file to a colleague and it just works for them too. You can even add a shebang line (#!/usr/bin/env -S uv run --script) and run it directly. The block is plain TOML inside comments, so any tool can read it. Here is the idea with only the standard library:

Pythonread_script_metadata.py
import reimport tomllib source = '''# /// script# requires-python = ">=3.12"# dependencies = [# "httpx>=0.28",# "rich>=13.9",# ]# ///import httpx''' match = re.search(r"^# /// script\n(.*?)^# ///$", source, re.S | re.M)toml_text = "".join(line[2:] + "\n" for line in match.group(1).splitlines())meta = tomllib.loads(toml_text)print("python:", meta["requires-python"])for dep in meta["dependencies"]: print("needs", dep)
Output
Press Run (⌘ Enter) to see what happens.

uvx for one-off tools

uvx (short for uv tool run) runs a command-line tool in a temporary, cached environment without adding it to your project or installing it globally:

uvx ruff check .              # lint any folder, no installuvx pycowsay "hello"          # try a tool onceuvx --from httpie http GET https://example.com   # package name differs from the commanduv run --with rich python     # a REPL with your project plus one extra package

Use uvx for tools you run occasionally, uv tool install for tools you use every day across projects, and uv add --dev for tools the project itself depends on, like the exact Ruff version CI uses.

Quick check
Your team's CI runs Ruff, and everyone must use the same Ruff version so formatting never flip-flops. How should Ruff be installed?
Need a nudge? A hint rules out a wrong answer.

Migrating from pip and requirements.txt

Moving an older project is usually a ten-minute job:

uv init --bare                         # add a minimal pyproject.toml, nothing elseuv add -r requirements.txt             # import runtime dependenciesuv add --dev -r requirements-dev.txt   # import dev toolsuv run pytest                          # prove it still works

Then delete the old requirements files, update the README, CI and Dockerfile to use uv sync, and commit pyproject.toml and uv.lock together. One clean-up worth doing: pip freeze output lists every indirect package with an exact pin. After importing, trim pyproject.toml back to the packages your code actually imports, with ranges, and let the lockfile handle the rest. If a deploy platform still insists on a requirements file, generate it instead of maintaining it: uv export --format requirements.txt.

Key terms
dependency group
A named list of development-only dependencies under [dependency-groups], like dev or docs.
universal lockfile
A lock that covers every platform and supported Python at once, with markers for platform-specific packages.
uv sync
Make .venv match uv.lock exactly, installing missing packages and removing extras.
--locked vs --frozen
--locked fails if the lock is stale; --frozen uses the lock as-is without checking.
inline script metadata
A # /// script comment block (PEP 723) listing a single file's Python version and dependencies.
uvx
Run a command-line tool once in a temporary cached environment, without installing it.