Sub topic 2
Development Dependencies and Dependency Groups
Assume you know basic Python, imports, packages, virtual environments, and terminal commands. This chapter uses an existing project created with uv init.
Keep development tools separate
A runtime dependency is needed when users run your application. A development dependency is needed only while you build or test it. uv records development dependencies in a dependency group.
uv add httpx
uv add --dev pytest
uv remove --dev pytestThe commands update pyproject.toml and resolve the environment. A typical project contains:
[project]
name = "weather-cli"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["httpx>=0.27"]
[dependency-groups]
dev = ["pytest>=8"]| Dependency kind | Example | Installed for users? |
|---|---|---|
| Runtime | `httpx` | Yes |
| Development | `pytest` | Usually no |
You can define additional groups when a project needs them, such as docs or lint.
Understand `uv.lock`
pyproject.toml states the dependency requirements. uv.lock records the exact resolved versions and compatible artifacts for those requirements, including transitive dependencies.
Update it after changing dependencies:
uv lockCommit uv.lock to version control for an application or service. In CI, require it to be current:
uv sync --lockedUse --frozen when you want uv to use the lockfile without checking whether it needs to be updated. --locked is usually better for CI because it detects an out-of-date lockfile.
Sync and run in the project environment
uv sync installs the locked project dependencies and normally includes the dev group:
uv sync
uv run pytestuv run executes a command using the project environment. It can also run your application:
uv run python -c "import httpx; print(httpx.__version__)"This avoids manually activating a virtual environment and ensures the command uses the project’s resolved packages.
Define a command-line entry point
An entry point maps a shell command to a Python function:
[project.scripts]
weather = "weather_cli:main"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"Create src/weather_cli/__init__.py:
import typer
def main() -> None:
typer.echo("Sunny")After adding typer, sync and run the command:
uv add typer
uv sync
uv run weatheruv run weather finds the installed project and calls weather_cli.main.
Exercise
Which command should CI use when it must reject an out-of-date lockfile?
Show answer
uv sync --locked.