Sub topic 4
Choosing and pinning a Python version
This chapter assumes you can create a project with uv init and have read about the [project] table in pyproject.toml. It covers two separate settings that people often confuse, and how uv picks an interpreter from them.
Two settings, two jobs
requires-pythoninpyproject.tomlsays which versions your code supports. It is a range, such as>=3.12..python-versionsays which version you use for development. It is a single request, such as3.12.
The range is part of your published metadata. The pin is a local choice for your working copy.
[project]
name = "weather-cli"
version = "0.1.0"
requires-python = ">=3.12"Pinning a version
uv python pin writes the .python-version file in the current directory.
uv python pin 3.12
cat .python-versionThe file contains the single line 3.12. Commit it so everyone on the project, and your CI, starts from the same interpreter.
Installing and finding interpreters
uv can download Python builds itself. You rarely need to do this by hand, because uv run and uv sync fetch a missing interpreter when needed. Explicit commands are useful for checking what you have.
uv python install 3.12
uv python list
uv python finduv python installdownloads a managed interpreter.uv python listshows installed and downloadable versions.uv python findprints the interpreter uv would use in the current directory.
How uv picks an interpreter
When you change the pin, the next uv run or uv sync rebuilds .venv on the new interpreter. You don't have to delete it yourself.
Why requires-python affects the lockfile
uv resolves dependencies so that uv.lock works for every Python version in your requires-python range, not only the one you run. If you write >=3.8 but a dependency needs 3.10 or later, resolution fails or picks older releases. Set the lower bound to the oldest version you actually test.
Common errors
- Pin outside the range. If
.python-versionsays3.11andrequires-pythonis>=3.12, uv reports the mismatch. Change the pin or widen the range. - A range that is too wide. The lock must satisfy all those versions, so you may get older dependency releases than you expect.
- Downloads blocked. Offline machines or CI with
UV_PYTHON_DOWNLOADS=neverneed the interpreter installed in advance.
Exercise
Your pyproject.toml has requires-python = ">=3.11" and your .python-version contains 3.13. You run uv run pytest. Which interpreter does uv use, and what happens if 3.13 is not installed?
Show answer
uv uses 3.13, because .python-version takes priority over the requires-python range and 3.13 satisfies the range. If 3.13 is not installed, uv downloads a managed 3.13 (unless downloads are disabled), rebuilds .venv if needed, and then runs the tests.