Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 16 / Topic 4 of 6

uv: one fast tool for all of this

Part 7 mentioned uv briefly as "pip + venv in one tool, try it later." Here is "later." uv (from Astral, the makers of Ruff) also replaces the manual pyproject.toml-editing and locking workflow: one tool for creating a project, adding dependencies, running code in the right environment, and building/publishing it.

This topic's commands were run for real with uv 0.11.24 while writing this lesson. Check your own version with uv --version; flags can change between releases, so uv <command> --help is always the source of truth.

Starting a project — uv init creates pyproject.toml, a starter script, a .venv is created lazily on first use, and (if you did not ask for --no-readme) a README.md:

$ uv init --app expense-cli
Initialized project `expense-cli` at `/.../expense-cli`
$ cat expense-cli/pyproject.toml
[project]
name = "expense-cli"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.14"
dependencies = []

--app sets up a runnable application (a main.py with a main() function); --lib instead sets up an importable library with a src/ layout and py.typed marker file, out of the box:

$ uv init --lib rupee-lib
$ find rupee-lib/src -maxdepth 3
rupee-lib/src
rupee-lib/src/rupee_lib
rupee-lib/src/rupee_lib/__init__.py
rupee-lib/src/rupee_lib/py.typed

Notice --lib's pyproject.toml picks uv_build as the [build-system] backend by default — uv ships its own build backend, so a simple project needs nothing extra installed to be built.

Adding a dependency — uv add edits pyproject.toml, resolves versions, creates .venv if it does not exist yet, and writes a lock file (uv.lock: the exact versions resolved, for everyone to reproduce):

$ cd expense-cli && uv add colorama
Using CPython 3.14.8 interpreter at: /opt/homebrew/opt/[email protected]/bin/python3.14
Creating virtual environment at: .venv
Resolved 2 packages in 224ms   (varies)
Prepared 1 package in 258ms   (varies)
Installed 1 package in 4ms   (varies)
 + colorama==0.4.6
$ cat pyproject.toml
...
dependencies = [
    "colorama>=0.4.6",
]

dependencies got the loose constraint (>=0.4.6, so it can still move forward); uv.lock separately pins the exact version everyone installing this project will get, until someone deliberately updates it.

Running code — uv run runs a command inside the project's own .venv, creating/updating it first if pyproject.toml changed since the last run. You never type source .venv/bin/activate at all:

$ uv run main.py
Hello from expense-cli!
$ uv run python --version
Python 3.14.8

Locking, on demand — uv lock re-resolves and rewrites uv.lock without installing anything (useful in CI, or after hand-editing pyproject.toml); uv sync makes .venv match the lock file exactly (installs missing packages, removes ones no longer listed).

Bumping the version — uv version reads or writes the [project] version field directly, so you do not hand-edit it:

$ uv version --bump patch
Resolved 2 packages in 216ms   (varies)
Checked 1 package in 0.97ms   (varies)
expense-cli 0.1.0 => 0.1.1
Classic tool Job uv equivalent
python -m venv .venv make a venv automatic, on first uv run/uv add
pip install x add a dependency uv add x (also edits pyproject.toml)
pip install -r requirements.txt restore exact versions uv sync (reads uv.lock)
pip freeze > requirements.txt pin exact versions uv lock (writes uv.lock)
source .venv/bin/activate && python f.py run inside the venv uv run f.py
python -m build build a wheel/sdist uv build
twine upload dist/* publish uv publish

You do not have to choose forever: uv reads and writes an ordinary pyproject.toml, so a project started with venv + pip can switch to uv later (and back), and either way the file a teammate without uv sees is still a standard pyproject.toml and (if you export it) requirements.txt.

Read more: the official uv documentation.

Exercise 4: Turn dependencies into install commands

Scenario: A teammate without uv wants plain pip install commands for a project's dependencies and its optional extras (dev, docs, ...). What to do: Parse the TOML text below with tomllib.loads(), then:

  1. Write runtime_install_command(data): one pip install "pkg1" "pkg2" ... line from [project.dependencies].
  2. Write extra_install_command(data, group): a line installing "<name>[<group>]", with a trailing comment listing what that group actually installs.
  3. Print the runtime command, then one extra command per group in [project.optional-dependencies], sorted by group name.
  4. Finally print one command that installs the project with every extra group at once: "<name>[group1,group2]".

Starting data:

PYPROJECT_TEXT = """
[project]
name = "weather-cli"
version = "0.3.0"
dependencies = ["requests>=2.32", "rich>=13.0"]

[project.optional-dependencies]
dev = ["pytest>=8.0", "ruff>=0.5"]
docs = ["mkdocs>=1.6"]
"""

Sample output:

Runtime dependencies:
  pip install "requests>=2.32" "rich>=13.0"
Extra group 'dev':
  pip install "weather-cli[dev]"  # installs: pytest>=8.0, ruff>=0.5
Extra group 'docs':
  pip install "weather-cli[docs]"  # installs: mkdocs>=1.6
Install project + every extra:
  pip install "weather-cli[dev,docs]"

💡 Hint: sorted(data["project"]["optional-dependencies"]) sorts the group names (the dict keys), not their contents.


Show the solution to Exercise 4
"""Exercise 4: Turning pyproject.toml dependencies into install commands.

Run:   python ex04.py   (macOS/Linux: python3 ex04.py)
"""

import tomllib

PYPROJECT_TEXT = """
[project]
name = "weather-cli"
version = "0.3.0"
dependencies = ["requests>=2.32", "rich>=13.0"]

[project.optional-dependencies]
dev = ["pytest>=8.0", "ruff>=0.5"]
docs = ["mkdocs>=1.6"]
"""


def runtime_install_command(data: dict) -> str:
    deps = data["project"]["dependencies"]
    return "pip install " + " ".join(f'"{dep}"' for dep in deps)


def extra_install_command(data: dict, group: str) -> str:
    deps = data["project"]["optional-dependencies"][group]
    name = data["project"]["name"]
    return f'pip install "{name}[{group}]"  # installs: ' + ", ".join(deps)


def main() -> None:
    data = tomllib.loads(PYPROJECT_TEXT)

    print("Runtime dependencies:")
    print(" ", runtime_install_command(data))

    for group in sorted(data["project"]["optional-dependencies"]):
        print(f"Extra group '{group}':")
        print(" ", extra_install_command(data, group))

    all_extra_groups = sorted(data["project"]["optional-dependencies"])
    everything = f"{data['project']['name']}[{','.join(all_extra_groups)}]"
    print("Install project + every extra:")
    print(f'  pip install "{everything}"')


if __name__ == "__main__":
    main()

Search the guide