
Uv
- 46 installs
- 6 repo stars
- Updated July 22, 2026
- julianobarbosa/claude-code-skills
Guide for using uv - extremely fast Python package and project manager written in Rust. Use when installing Python, managing venv, adding dependencies, running scripts.
About
Guide for uv - extremely fast Python package and project manager in Rust.. Use for Python install, venv management, dependency management, script running.
- beginner skill
- core: python
Uv by the numbers
- 46 all-time installs (skills.sh)
- +1 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #157 of 290 Python skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/julianobarbosa/claude-code-skills --skill uvAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 46 |
|---|---|
| repo stars | ★ 6 |
| Last updated | July 22, 2026 |
| Repository | julianobarbosa/claude-code-skills ↗ |
What it does
Guide for using uv - extremely fast Python package and project manager written in Rust. Use when installing Python, managing venv, adding dependencies, running scripts.
Files
uv Skill
Extremely fast Python package and project manager by Astral (Ruff creators).
Overview
uv is a single tool that replaces:
- pip/pip-tools - Package installation and dependency resolution
- virtualenv/venv - Virtual environment creation
- pyenv - Python version management
- pipx - Tool installation and execution
- poetry/pdm - Project and dependency management
- twine - Package publishing
Key Features:
- 10-100x faster than pip
- Universal lockfile (
uv.lock) for reproducible builds - Automatic Python version management
- Built-in tool execution (
uvx) - PEP 723 inline script dependencies
- Drop-in pip compatibility
Quick Reference
| Task | Command |
|---|---|
| New project | uv init |
| New library | uv init --lib |
| Add package | uv add <pkg> |
| Add dev dependency | uv add --dev <pkg> |
| Remove package | uv remove <pkg> |
| Install all deps | uv sync |
| Install (CI/prod) | uv sync --locked |
| Run command | uv run <cmd> |
| Run tool (no install) | uvx <tool> |
| Install Python | uv python install 3.12 |
| Pin Python version | uv python pin 3.12 |
| Update all deps | uv lock --upgrade |
| Update one package | uv lock --upgrade-package <pkg> |
| Show dep tree | uv tree |
| Build package | uv build |
| Publish to PyPI | uv publish |
Quick Start
Installation
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# Via pip/pipx
pipx install uv
pip install uv
# Homebrew
brew install uvShell Completion
# Bash
echo 'eval "$(uv generate-shell-completion bash)"' >> ~/.bashrc
# Zsh
echo 'eval "$(uv generate-shell-completion zsh)"' >> ~/.zshrc
# Fish
echo 'uv generate-shell-completion fish | source' > ~/.config/fish/completions/uv.fishEssential Commands
1. Starting a Project
# Create new project
uv init my-project # Application (default)
uv init --lib my-library # Library (src layout, build backend)
uv init --app my-app # Explicit application
# Set Python version
uv python pin 3.12 # Creates .python-version
# Install Python if needed
uv python install 3.122. Managing Dependencies
# Add packages
uv add requests flask # Production dependencies
uv add --dev pytest ruff # Development dependencies
uv add --group test pytest # Specific dependency group
uv add --optional api flask # Optional extra
uv add "httpx>=0.20" # With version constraint
# Remove packages
uv remove requests
uv remove --dev pytest
# Update packages
uv lock --upgrade # All packages
uv lock --upgrade-package requests # Single package
# View dependencies
uv tree # Full tree
uv tree --depth 2 # Limited depth3. Syncing Environment
# Install all dependencies
uv sync # Default (includes dev)
uv sync --locked # CI/production (strict)
uv sync --frozen # Don't update lockfile
uv sync --no-dev # Exclude dev dependencies
uv sync --all-extras # Include optional extras4. Running Code
# Run in project environment
uv run python script.py
uv run pytest
uv run flask run
# Run with temporary dependency
uv run --with pandas script.py
# Run tools without installing (uvx)
uvx ruff check .
uvx black --check .
uvx --from httpie http https://example.com5. Python Version Management
# Install Python versions
uv python install # Latest version
uv python install 3.12 # Specific version
uv python install 3.11 3.12 3.13 # Multiple
# List versions
uv python list
uv python list --only-installed
# Pin version
uv python pin 3.12 # Project (.python-version)
uv python pin --global 3.12 # User default
# Find Python
uv python find
uv python find ">=3.11"6. Virtual Environments
# Create (usually automatic)
uv venv # Creates .venv
uv venv my-env # Custom name
uv venv --python 3.12 # Specific Python
# Activate (optional - uv run auto-detects)
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows7. Global Tools
# Install tools globally
uv tool install ruff
uv tool install "ruff==0.5.0"
uv tool install --python 3.12 mypy
# Manage tools
uv tool list
uv tool upgrade ruff
uv tool upgrade --all
uv tool uninstall ruff
# Setup PATH
uv tool update-shellScripts with Inline Dependencies (PEP 723)
# Initialize script with metadata
uv init --script example.py --python 3.12
# Add dependencies to script
uv add --script example.py requests rich
# Run script (dependencies auto-installed)
uv run example.pyScript format:
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "requests<3",
# "rich",
# ]
# ///
import requests
from rich import print
print(requests.get("https://api.example.com").json())pip-Compatible Interface
# Install packages (requires virtual environment)
uv pip install flask
uv pip install -r requirements.txt
uv pip install -e . # Editable install
# Uninstall
uv pip uninstall flask
# Compile requirements
uv pip compile requirements.in -o requirements.txt
# Sync from requirements
uv pip sync requirements.txt
# Freeze environment
uv pip freezeBuilding and Publishing
# Build distributions
uv build # Creates dist/ with wheel and sdist
# Publish to PyPI
uv publish # Requires authentication setup
# Authenticate
uv auth login pypi # Interactive login
uv auth login pypi --token # API tokenProject Structure
my-project/
├── pyproject.toml # Project definition (required)
├── uv.lock # Lock file (auto-generated)
├── .venv/ # Virtual environment (gitignored)
├── .python-version # Python version pin (optional)
└── src/
└── my_project/
└── __init__.pypyproject.toml Example
[project]
name = "my-project"
version = "0.1.0"
description = "My awesome project"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"requests>=2.28",
"click>=8.0",
]
[project.optional-dependencies]
api = ["fastapi", "uvicorn"]
dev = ["pytest", "ruff"]
[project.scripts]
my-cli = "my_project.cli:main"
[dependency-groups]
dev = ["pytest>=8", "ruff", "mypy"]
test = ["pytest-cov"]
docs = ["sphinx", "myst-parser"]
[tool.uv]
dev-dependencies = ["pytest", "ruff"] # Alternative to dependency-groups
default-groups = ["dev"]
[tool.uv.sources]
# Git dependency
my-lib = { git = "https://github.com/user/my-lib" }
# Local path
local-pkg = { path = "./packages/local-pkg" }
# Specific index
torch = { index = "pytorch" }
[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cpu"
explicit = trueConfiguration
Configuration Files
Project-level (highest priority):
uv.toml- Standalone config (preferred)pyproject.toml- Under[tool.uv]section
User-level:
~/.config/uv/uv.toml(macOS/Linux)%APPDATA%\uv\uv.toml(Windows)
Key Environment Variables
| Variable | Purpose |
|---|---|
UV_CACHE_DIR | Cache directory location |
UV_PYTHON | Default Python version |
UV_INDEX_URL | Default package index |
UV_NO_CACHE | Disable caching |
UV_FROZEN | Use lockfile without updating |
UV_LOCKED | Assert lockfile unchanged |
UV_COMPILE_BYTECODE | Compile to .pyc files |
UV_LINK_MODE | Package linking mode (copy, hardlink, symlink) |
Common Workflows
New Project Setup
# Create and enter project
uv init my-project
cd my-project
# Add dependencies
uv add flask sqlalchemy
uv add --dev pytest ruff mypy
# Run application
uv run flask run
# Run tests
uv run pytestExisting Project (from requirements.txt)
# Initialize uv project
uv init
# Import dependencies from requirements.txt
uv add $(cat requirements.txt | grep -v "^#" | tr '\n' ' ')
# Or use pip interface
uv venv
uv pip install -r requirements.txtCI/CD Pipeline
# GitHub Actions
- uses: astral-sh/setup-uv@v7
with:
enable-cache: true
- run: uv sync --locked
- run: uv run pytest# GitLab CI
variables:
UV_CACHE_DIR: .uv-cache
UV_LINK_MODE: copy
image: ghcr.io/astral-sh/uv:latest
script:
- uv sync --locked
- uv run pytestDocker
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
WORKDIR /app
COPY pyproject.toml uv.lock ./
# Install dependencies only (for caching)
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --locked --no-install-project
# Copy source and install project
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --locked
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "-m", "my_app"]direnv Integration
# .envrc
if has uv; then
VIRTUAL_ENV="$(pwd)/.venv"
if [[ ! -d "$VIRTUAL_ENV" ]]; then
uv venv
fi
PATH_add "$VIRTUAL_ENV/bin"
export VIRTUAL_ENV
fiMigration Guide
From pip + requirements.txt
# Option 1: Initialize new uv project and import dependencies
uv init
# Extract package names from requirements.txt
cat requirements.txt | grep -v "^#" | grep -v "^-e" | \
cut -d'=' -f1 | cut -d'>' -f1 | xargs uv add
# Option 2: Keep using requirements.txt with uv's pip interface
uv venv
uv pip install -r requirements.txt
# Option 3: Generate lockfile from requirements.txt
uv pip compile requirements.in -o requirements.txtKey differences:
uv.lockreplacesrequirements.txtfor lockingpyproject.tomlreplacesrequirements.infor declaring dependencies- Use
uv runinstead of activating virtualenv
From Poetry
# uv can read Poetry's pyproject.toml format
cd existing-poetry-project
# Initialize uv (keeps existing pyproject.toml)
uv sync
# Poetry sections are automatically recognized:
# [tool.poetry.dependencies] -> project dependencies
# [tool.poetry.group.dev.dependencies] -> dev dependenciesMigrate pyproject.toml (optional but recommended):
# Poetry format
[tool.poetry.dependencies]
python = "^3.11"
requests = "^2.28"
[tool.poetry.group.dev.dependencies]
pytest = "^8.0"
# Standard format (uv native)
[project]
requires-python = ">=3.11"
dependencies = ["requests>=2.28"]
[dependency-groups]
dev = ["pytest>=8.0"]Command equivalents:
| Poetry | uv |
|---|---|
poetry install | uv sync |
poetry add requests | uv add requests |
poetry add -D pytest | uv add --dev pytest |
poetry remove requests | uv remove requests |
poetry run pytest | uv run pytest |
poetry lock | uv lock |
poetry build | uv build |
poetry publish | uv publish |
From Pipenv
# Convert Pipfile to requirements.txt first
pipenv requirements > requirements.txt
pipenv requirements --dev > requirements-dev.txt
# Initialize uv project and import
uv init
cat requirements.txt | grep -v "^#" | xargs uv add
cat requirements-dev.txt | grep -v "^#" | xargs uv add --dev
# Remove old Pipenv files after verification
rm Pipfile Pipfile.lockCommand equivalents:
| Pipenv | uv |
|---|---|
pipenv install | uv sync |
pipenv install requests | uv add requests |
pipenv install --dev pytest | uv add --dev pytest |
pipenv run pytest | uv run pytest |
pipenv lock | uv lock |
pipenv shell | source .venv/bin/activate (or use uv run) |
From pyenv (Python version management only)
# Install Python versions with uv instead
uv python install 3.11 3.12 3.13
# Pin version for project (creates .python-version)
uv python pin 3.12
# List installed versions
uv python list --only-installed
# uv reads existing .python-version files from pyenvNote: You can use pyenv and uv together - uv will detect pyenv-installed Pythons.
From conda
uv does not replace conda for:
- Non-Python dependencies (C libraries, CUDA, etc.)
- Conda-specific packages not on PyPI
For pure Python projects:
# Export conda environment
conda list --export > conda-packages.txt
# Extract Python packages (filter conda-specific ones)
grep -v "^#" conda-packages.txt | grep -v "conda" | cut -d'=' -f1 > packages.txt
# Initialize uv and add packages
uv init
uv add $(cat packages.txt | tr '\n' ' ')Hybrid approach: Use conda for system dependencies, uv for Python packages:
# Conda for non-Python deps
conda create -n myenv python=3.12 cudatoolkit
# Activate conda env, then use uv
conda activate myenv
export UV_SYSTEM_PYTHON=1
uv pip install -r requirements.txtCommon Pitfalls
1. Forgetting --locked in CI/Production
# Wrong - may update lockfile unexpectedly
uv sync
# Correct - fails if lockfile is outdated (reproducible builds)
uv sync --locked2. Mixing uv and pip Commands
# Don't do this - breaks uv's dependency tracking
pip install some-package
source .venv/bin/activate && pip install another-package
# Do this instead - uv tracks all dependencies
uv add some-package
# Or use uv's pip interface if needed
uv pip install some-package3. Not Committing uv.lock
The uv.lock file must be committed to version control for reproducible builds. Without it, environments may resolve differently.
# .gitignore - DON'T ignore uv.lock
.venv/
__pycache__/
# uv.lock <-- DO NOT ADD THIS LINE4. Running Commands Outside Project Environment
# Wrong - uses system Python, not project environment
python script.py
pytest
# Correct - runs within project's virtual environment
uv run python script.py
uv run pytest5. Editing uv.lock Manually
Never edit uv.lock by hand. It's auto-generated and managed by uv.
# To update a specific package
uv lock --upgrade-package requests
# To upgrade all packages
uv lock --upgrade
# To regenerate from scratch
rm uv.lock && uv lock6. Using --frozen When You Mean --locked
# --frozen: Don't update lockfile, but don't verify it either
uv sync --frozen
# --locked: Verify lockfile matches pyproject.toml (use this in CI)
uv sync --lockedTroubleshooting
Common Issues
| Issue | Cause | Solution |
|---|---|---|
No pyproject.toml | Wrong directory | cd to root or uv init |
| Package not found | Wrong index/typo | Check name, try --index |
| Lockfile outdated | pyproject changed | Run uv lock |
Resolver conflict | Version conflicts | Try uv lock --upgrade |
| Python mismatch | Not installed | uv python install 3.12 |
| Build failures | Missing deps | Try --no-build-isolation |
| Hash mismatch | Corrupted cache | uv cache clean |
| Slow first run | Cold cache | Normal, uses cache after |
Debug Commands
# Check current environment
uv python find
uv pip list
# Verbose output
uv sync -v
uv sync -vv # More verbose
# Check lockfile status
uv lock --check
# Clear cache
uv cache clean
uv cache prune --ci # For CI environmentsReferences
references/cli-commands.md- Complete CLI referencereferences/project-management.md- Project and dependency managementreferences/python-versions.md- Python version managementreferences/integrations.md- Docker, CI/CD, and tool integrations
External Links
- Official docs: <https://docs.astral.sh/uv/>
- GitHub: <https://github.com/astral-sh/uv>
- Docker images: <https://github.com/astral-sh/uv/pkgs/container/uv>
- Changelog: <https://github.com/astral-sh/uv/blob/main/CHANGELOG.md>
---
Absorbed sub-skill (post-consolidation)
This skill now subsumes the former python-project skill (project scaffolding). Original content preserved under:
| Subject | Path |
|---|---|
| Python project scaffolding (Flask/pytest patterns, project structure) | References/python-project.md |
| Project references | References/python-project-references/ |
| Project scripts | References/python-project-scripts/ |
---
Gotchas
- `uv pip install -e .` works but doesn't write the editable install to `uv.lock` — the lockfile is wrong on next
uv sync. Useuv add --editableinstead. - `uv sync --frozen` fails if dependencies upgraded outside the lock — won't auto-update; emit a clear error message but blocks CI until you
uv lock --upgrade-package <name>. - `uv venv` creates `.venv` in CWD — missing
--directoryaftercdputs the venv in the wrong place. Pin withUV_PROJECT_ENVIRONMENTenv var or absolute paths in scripts. - `uv tool install` and `uv pip install` go to DIFFERENT environments — uv tools are isolated per-tool; pip-installed packages aren't visible to uv-installed tools.
- Pin via `==X.Y.Z` in `pyproject.toml` doesn't lock; only `uv.lock` does —
dependencies = ["foo==1.2.3"]allows uv to pick any compatible 1.2.3, including yanked versions.
uv CLI Reference
Complete command reference for uv - the Python package and project manager.
Command Structure
uv [OPTIONS] <COMMAND>Top-Level Commands
| Command | Description |
|---|---|
uv init | Create a new project |
uv add | Add dependencies to the project |
uv remove | Remove dependencies from the project |
uv sync | Update the project's environment |
uv lock | Update the project's lockfile |
uv run | Run a command or script |
uv tree | Display the project's dependency tree |
uv export | Export the project's lockfile to alternate formats |
uv version | Read or update the project's version |
uv format | Format Python code in the project |
uv tool | Run and install commands provided by Python packages |
uv python | Manage Python versions and installations |
uv pip | Manage Python packages with pip-compatible interface |
uv venv | Create a virtual environment |
uv build | Build Python packages into distributions |
uv publish | Upload distributions to an index |
uv cache | Manage uv's cache |
uv auth | Manage authentication |
uv self | Manage the uv executable |
uv help | Display documentation for a command |
---
Project Commands
uv init
Create a new project.
uv init [OPTIONS] [PATH]Options:
| Option | Description |
|---|---|
--name <NAME> | Project name (defaults to directory name) |
--package | Create a Python package (default) |
--app | Create an application project |
--lib | Create a library project |
--script | Create a standalone script with inline metadata |
--python <VERSION> | Python version requirement |
--no-readme | Skip README.md creation |
--no-pin-python | Don't create .python-version |
--build-backend <BACKEND> | Build backend (hatchling, flit-core, etc.) |
--vcs <VCS> | Initialize version control (git, none) |
Examples:
uv init my-project
uv init --lib my-library
uv init --app --python 3.12 my-app
uv init --script example.pyuv add
Add dependencies to the project.
uv add [OPTIONS] <PACKAGES>...Options:
| Option | Description |
|---|---|
--dev | Add to development dependencies |
--group <GROUP> | Add to specific dependency group |
--optional <EXTRA> | Add as optional dependency (extra) |
--script <SCRIPT> | Add to inline script metadata |
--editable | Install as editable package |
--no-sync | Don't sync after adding |
--frozen | Don't update lockfile |
--locked | Assert lockfile unchanged |
--upgrade-package <PKG> | Upgrade specific package |
--index <URL> | Package index for this dependency |
--python <VERSION> | Python version for resolution |
Examples:
uv add requests flask
uv add "httpx>=0.20,<1.0"
uv add --dev pytest ruff mypy
uv add --group test pytest-cov
uv add --optional api fastapi uvicorn
uv add --script example.py pandas
uv add "git+https://github.com/user/repo"
uv add torch --index https://download.pytorch.org/whl/cpuuv remove
Remove dependencies from the project.
uv remove [OPTIONS] <PACKAGES>...Options:
| Option | Description |
|---|---|
--dev | Remove from development dependencies |
--group <GROUP> | Remove from specific group |
--optional <EXTRA> | Remove from optional dependencies |
--script <SCRIPT> | Remove from inline script metadata |
--no-sync | Don't sync after removing |
Examples:
uv remove requests
uv remove --dev pytest
uv remove --group test pytest-covuv sync
Update the project's environment.
uv sync [OPTIONS]Options:
| Option | Description |
|---|---|
--frozen | Don't update lockfile |
--locked | Assert lockfile unchanged |
--no-dev | Exclude dev dependencies |
--only-dev | Only dev dependencies |
--group <GROUP> | Include specific group |
--no-group <GROUP> | Exclude specific group |
--all-groups | Include all groups |
--no-default-groups | Exclude default groups |
--extra <EXTRA> | Include optional dependency |
--all-extras | Include all optional dependencies |
--no-install-project | Don't install the project itself |
--no-install-workspace | Don't install workspace members |
--no-editable | Install as non-editable |
--exact | Remove extraneous packages |
--inexact | Keep extraneous packages |
--python <VERSION> | Python version |
Examples:
uv sync
uv sync --locked
uv sync --no-dev --all-extras
uv sync --group test --group lint
uv sync --no-install-project # Dependencies only (Docker caching)uv lock
Update the project's lockfile.
uv lock [OPTIONS]Options:
| Option | Description |
|---|---|
--check | Check if lockfile is up-to-date |
--upgrade | Upgrade all packages |
--upgrade-package <PKG> | Upgrade specific package |
--script <SCRIPT> | Lock script dependencies |
--python <VERSION> | Python version |
Examples:
uv lock
uv lock --check # CI validation
uv lock --upgrade
uv lock --upgrade-package requests
uv lock --script example.pyuv run
Run a command or script in the project environment.
uv run [OPTIONS] [COMMAND]...Options:
| Option | Description |
|---|---|
--with <PKG> | Add temporary dependency |
--with-requirements <FILE> | Add temporary requirements |
--module, -m | Run Python module |
--script | Run as script |
--isolated | Run in isolated environment |
--no-sync | Don't sync environment |
--no-project | Ignore project context |
--frozen | Don't update lockfile |
--locked | Assert lockfile unchanged |
--active | Prefer active virtual environment |
--env-file <FILE> | Load .env file |
--python <VERSION> | Python version |
--all-extras | Include all optional dependencies |
--extra <EXTRA> | Include specific extra |
--group <GROUP> | Include specific group |
--no-dev | Exclude dev dependencies |
Examples:
uv run python script.py
uv run pytest -v
uv run --with pandas python analyze.py
uv run -m my_module
uv run --isolated ruff check .
uv run --env-file .env.local python app.py
echo 'print("hello")' | uv run -uv tree
Display the project's dependency tree.
uv tree [OPTIONS]Options:
| Option | Description |
|---|---|
--depth <N> | Maximum display depth |
--package <PKG> | Focus on specific package |
--prune <PKG> | Prune specific packages |
--invert | Show reverse dependencies |
--no-dev | Exclude dev dependencies |
Examples:
uv tree
uv tree --depth 2
uv tree --package requests
uv tree --invert --package urllib3uv export
Export the lockfile to alternate formats.
uv export [OPTIONS]Options:
| Option | Description |
|---|---|
--format <FORMAT> | Output format (requirements-txt, pylock.toml) |
--output-file, -o <FILE> | Output file path |
--no-hashes | Exclude hashes |
--no-dev | Exclude dev dependencies |
--all-extras | Include all extras |
--extra <EXTRA> | Include specific extra |
Examples:
uv export --format requirements-txt -o requirements.txt
uv export --format pylock.toml
uv export --format cyclonedx1.5 -o sbom.json---
Python Management Commands
uv python install
Install Python versions.
uv python install [OPTIONS] [VERSIONS]...Options:
| Option | Description |
|---|---|
--default | Install as default (python, python3 executables) |
--reinstall | Reinstall existing versions |
--preview | Include preview releases |
Examples:
uv python install
uv python install 3.12
uv python install 3.11 3.12 3.13
uv python install pypy
uv python install 3.12 --defaultuv python list
List available and installed Python versions.
uv python list [OPTIONS] [VERSION]Options:
| Option | Description |
|---|---|
--only-installed | Show only installed versions |
--all-versions | Include all patch versions |
--all-platforms | Show downloads for all platforms |
Examples:
uv python list
uv python list --only-installed
uv python list 3.12
uv python list pypyuv python pin
Pin Python version for the project.
uv python pin [OPTIONS] <VERSION>Options:
| Option | Description |
|---|---|
--global | Pin globally (user-level) |
--resolved | Pin exact resolved version |
Examples:
uv python pin 3.12
uv python pin --global 3.12
uv python pin 3.12.5 --resolveduv python find
Find Python executable.
uv python find [OPTIONS] [VERSION]Options:
| Option | Description |
|---|---|
--system | Ignore virtual environments |
--no-project | Ignore project requirements |
Examples:
uv python find
uv python find ">=3.11"
uv python find 3.12uv python upgrade
Upgrade Python installations.
uv python upgrade [OPTIONS] [VERSIONS]...Examples:
uv python upgrade 3.12 # Upgrade to latest 3.12.x
uv python upgrade # Upgrade all installeduv python uninstall
Uninstall Python versions.
uv python uninstall <VERSIONS>...Examples:
uv python uninstall 3.11
uv python uninstall 3.11 3.12---
Tool Commands
uv tool run (uvx)
Run a tool without installing.
uvx [OPTIONS] <COMMAND>...
uv tool run [OPTIONS] <COMMAND>...Options:
| Option | Description |
|---|---|
--from <PKG> | Package to run from |
--with <PKG> | Additional dependencies |
--python <VERSION> | Python version |
--isolated | Ignore installed version |
Examples:
uvx ruff check .
uvx black --check .
uvx --from httpie http https://api.example.com
uvx ruff@0.5.0 check .
uvx --with mkdocs-material mkdocs build
uvx --python 3.12 mypy .uv tool install
Install a tool globally.
uv tool install [OPTIONS] <PACKAGE>Options:
| Option | Description |
|---|---|
--with <PKG> | Additional packages |
--with-editable <PKG> | Additional editable packages |
--python <VERSION> | Python version |
--force | Overwrite existing executables |
--reinstall | Reinstall if already installed |
Examples:
uv tool install ruff
uv tool install "ruff==0.5.0"
uv tool install ruff --python 3.12
uv tool install mkdocs --with mkdocs-materialuv tool list
List installed tools.
uv tool list [OPTIONS]Options:
| Option | Description |
|---|---|
--show-paths | Show executable paths |
uv tool upgrade
Upgrade installed tools.
uv tool upgrade [OPTIONS] [TOOL]Options:
| Option | Description |
|---|---|
--all | Upgrade all tools |
--upgrade-package <PKG> | Upgrade specific dependency |
--reinstall | Reinstall packages |
Examples:
uv tool upgrade ruff
uv tool upgrade --alluv tool uninstall
Uninstall a tool.
uv tool uninstall <TOOL>uv tool update-shell
Update shell configuration for tool PATH.
uv tool update-shell---
Virtual Environment Commands
uv venv
Create a virtual environment.
uv venv [OPTIONS] [PATH]Options:
| Option | Description |
|---|---|
--python <VERSION> | Python version |
--system-site-packages | Allow access to system packages |
--seed | Install seed packages (pip, setuptools) |
--relocatable | Make environment relocatable |
--prompt <NAME> | Custom prompt name |
Examples:
uv venv
uv venv .venv
uv venv --python 3.12 my-env
uv venv --seed # Include pip---
pip Interface Commands
uv pip install
Install packages.
uv pip install [OPTIONS] <PACKAGES>...Options:
| Option | Description |
|---|---|
-r, --requirement <FILE> | Requirements file |
-e, --editable <PATH> | Editable install |
-c, --constraint <FILE> | Constraint file |
--index-url <URL> | Package index |
--extra-index-url <URL> | Additional index |
--no-deps | Don't install dependencies |
--no-binary <PKG> | Build from source |
--only-binary <PKG> | Only use wheels |
--upgrade, -U | Upgrade packages |
--reinstall | Reinstall packages |
--system | Use system Python |
--python <VERSION> | Target Python |
Examples:
uv pip install flask
uv pip install -r requirements.txt
uv pip install -e .
uv pip install --upgrade requestsuv pip uninstall
Uninstall packages.
uv pip uninstall [OPTIONS] <PACKAGES>...uv pip compile
Compile requirements.
uv pip compile [OPTIONS] <SRC>...Options:
| Option | Description |
|---|---|
-o, --output-file <FILE> | Output file |
--upgrade | Upgrade all packages |
--upgrade-package <PKG> | Upgrade specific package |
--no-header | Omit header comment |
--generate-hashes | Include hashes |
--all-extras | Include all extras |
Examples:
uv pip compile requirements.in -o requirements.txt
uv pip compile pyproject.toml -o requirements.txt
uv pip compile requirements.in --upgradeuv pip sync
Sync environment with requirements.
uv pip sync [OPTIONS] <REQUIREMENTS>...Examples:
uv pip sync requirements.txtuv pip freeze
List installed packages.
uv pip freeze [OPTIONS]uv pip list
List installed packages.
uv pip list [OPTIONS]Options:
| Option | Description |
|---|---|
--editable | Only editable packages |
--exclude-editable | Exclude editable packages |
--outdated | Show outdated packages |
--format <FORMAT> | Output format (columns, freeze, json) |
uv pip show
Show package information.
uv pip show <PACKAGES>...uv pip check
Verify installed packages have compatible dependencies.
uv pip check---
Build and Publish Commands
uv build
Build distributions.
uv build [OPTIONS] [SRC]Options:
| Option | Description |
|---|---|
--wheel | Build only wheel |
--sdist | Build only source distribution |
--out-dir, -o <DIR> | Output directory |
--python <VERSION> | Python version |
--no-build-isolation | Disable build isolation |
Examples:
uv build
uv build --wheel
uv build -o dist/uv publish
Publish distributions.
uv publish [OPTIONS] [DIST]...Options:
| Option | Description |
|---|---|
--repository <URL> | Repository URL |
--token <TOKEN> | API token |
--username <USER> | Username |
--password <PASS> | Password |
--check-url <URL> | Check if version exists |
Examples:
uv publish
uv publish dist/*
uv publish --token $PYPI_TOKEN---
Cache Commands
uv cache clean
Clear cache.
uv cache clean [PACKAGES]...uv cache prune
Remove outdated cache entries.
uv cache prune [OPTIONS]Options:
| Option | Description |
|---|---|
--ci | Aggressive pruning for CI |
uv cache dir
Show cache directory path.
uv cache dir---
Authentication Commands
uv auth login
Authenticate with a service.
uv auth login [OPTIONS] <SERVICE>Options:
| Option | Description |
|---|---|
-u, --username <USER> | Username |
-t, --token | Use API token |
--password <PASS> | Password |
--keyring-provider <PROVIDER> | Credential backend |
Examples:
uv auth login pypi
uv auth login pypi --token
uv auth login https://private.pypi.orguv auth logout
Remove authentication.
uv auth logout [OPTIONS] <SERVICE>uv auth token
Show authentication token.
uv auth token <SERVICE>---
Global Options
Available for most commands:
| Option | Description |
|---|---|
-v, --verbose | Verbose output |
-q, --quiet | Quiet output |
--color <CHOICE> | Color output (auto, always, never) |
--no-progress | Hide progress bars |
--project <DIR> | Project directory |
--directory <DIR> | Working directory |
--config-file <FILE> | Config file path |
--no-config | Ignore config files |
--cache-dir <DIR> | Cache directory |
--no-cache | Disable caching |
--offline | Disable network access |
--python <VERSION> | Python version |
--managed-python | Require uv-managed Python |
--no-managed-python | Allow system Python |
--no-python-downloads | Don't download Python |
-h, --help | Show help |
---
Version Request Formats
uv accepts various Python version formats:
| Format | Example | Description |
|---|---|---|
| Version | 3.12, 3.12.5 | Specific version |
| Range | >=3.11,<3.13 | Version constraint |
| Variant | 3.13t, 3.13+freethreaded | Free-threaded |
| Debug | 3.13d, 3.13+debug | Debug build |
| Implementation | cpython, pypy | Python implementation |
| Path | /usr/bin/python3 | Executable path |
---
Environment Variables
See references/integrations.md for complete environment variable reference.
Key variables:
UV_CACHE_DIR- Cache directoryUV_PYTHON- Default Python versionUV_INDEX_URL/UV_DEFAULT_INDEX- Package indexUV_FROZEN- Use lockfile without updatingUV_LOCKED- Assert lockfile unchangedUV_LINK_MODE- Package linking modeUV_COMPILE_BYTECODE- Compile .pyc files
uv Integrations Reference
Comprehensive guide to integrating uv with Docker, CI/CD, tools, and other systems.
---
Docker Integration
Official Docker Images
Distroless (uv binary only):
ghcr.io/astral-sh/uv:latest
ghcr.io/astral-sh/uv:0.9.18
ghcr.io/astral-sh/uv:0.9With OS (Alpine):
ghcr.io/astral-sh/uv:alpine
ghcr.io/astral-sh/uv:alpine3.22With OS (Debian):
ghcr.io/astral-sh/uv:debian-slim
ghcr.io/astral-sh/uv:bookworm-slim
ghcr.io/astral-sh/uv:trixie-slimWith Python:
ghcr.io/astral-sh/uv:python3.12-bookworm-slim
ghcr.io/astral-sh/uv:python3.12-alpineInstalling uv in Dockerfile
Copy from distroless image (recommended):
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/Pin to specific version:
COPY --from=ghcr.io/astral-sh/uv:0.9.18 /uv /uvx /bin/Pin to SHA256:
# Use full SHA for reproducible builds
COPY --from=ghcr.io/astral-sh/uv@sha256:2381d6aa60c326b71... \
/uv /uvx /bin/Using installer script:
RUN apt-get update && apt-get install -y curl ca-certificates
ADD https://astral.sh/uv/install.sh /uv-installer.sh
RUN sh /uv-installer.sh && rm /uv-installer.sh
ENV PATH="/root/.local/bin/:$PATH"Basic Dockerfile Pattern
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
WORKDIR /app
COPY pyproject.toml uv.lock ./
ENV UV_NO_DEV=1
RUN uv sync --locked
COPY . .
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "-m", "my_app"]Multi-Stage Build (Optimized)
# Build stage
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
WORKDIR /app
# Install dependencies first (cache layer)
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --locked --no-install-project
# Copy source and sync project
COPY . /app
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --locked
# Runtime stage
FROM python:3.12-slim
COPY --from=builder /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "-m", "my_app"]Non-Editable Production Build
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --locked --no-install-project --no-editable
COPY . /app
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --locked --no-editable
FROM python:3.12-slim
COPY --from=builder /app/.venv /app/.venv
CMD ["/app/.venv/bin/my-app"]Docker Caching
# Enable cache mount
ENV UV_LINK_MODE=copy # Required for separate filesystems
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --lockedDocker Environment Variables
ENV UV_NO_DEV=1 # Exclude dev dependencies
ENV UV_COMPILE_BYTECODE=1 # Compile .pyc files
ENV UV_LINK_MODE=copy # Required for cache mounts
ENV UV_NO_CACHE=1 # Disable caching (smaller image).dockerignore
.venv/
__pycache__/
*.pyc
.git/
.pytest_cache/
.mypy_cache/
.ruff_cache/---
GitHub Actions
Basic Setup
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Set up Python
run: uv python install
- name: Install dependencies
run: uv sync --locked
- name: Run tests
run: uv run pytestWith Caching
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
version: "0.9.18" # Pin versionMatrix Testing
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v5
- uses: astral-sh/setup-uv@v7
with:
python-version: ${{ matrix.python-version }}
- run: uv sync --locked
- run: uv run pytestUsing setup-python (Faster)
- uses: actions/setup-python@v6
with:
python-version-file: ".python-version"
- uses: astral-sh/setup-uv@v7
with:
enable-cache: trueManual Caching
env:
UV_CACHE_DIR: /tmp/.uv-cache
jobs:
test:
steps:
- uses: actions/cache@v4
with:
path: /tmp/.uv-cache
key: uv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
restore-keys: |
uv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
uv-${{ runner.os }}
- run: uv sync --locked
- run: uv run pytest
- run: uv cache prune --ciPublishing to PyPI
name: Publish
on:
push:
tags:
- v*
jobs:
publish:
runs-on: ubuntu-latest
environment:
name: pypi
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v5
- uses: astral-sh/setup-uv@v7
- name: Build
run: uv build
- name: Publish
run: uv publish---
GitLab CI/CD
Basic Configuration
variables:
UV_VERSION: "0.9.18"
UV_CACHE_DIR: .uv-cache
UV_LINK_MODE: copy # Required for GitLab
test:
image: ghcr.io/astral-sh/uv:$UV_VERSION-python3.12-bookworm-slim
cache:
key:
files:
- uv.lock
paths:
- $UV_CACHE_DIR
script:
- uv sync --locked
- uv run pytest
- uv cache prune --ciDistroless Image
test:
image:
name: ghcr.io/astral-sh/uv:$UV_VERSION
entrypoint: [""] # Required for distroless
script:
- uv sync --lockedUsing System Python
variables:
UV_SYSTEM_PYTHON: 1
test:
image: python:3.12-slim
script:
- curl -LsSf https://astral.sh/uv/install.sh | sh
- export PATH="$HOME/.local/bin:$PATH"
- uv pip install -r requirements.txt---
Pre-Commit Hooks
Configuration
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/uv-pre-commit
rev: 0.9.18
hooks:
# Keep uv.lock in sync with pyproject.toml
- id: uv-lock
# Export to requirements.txt
- id: uv-exportCompile Requirements
repos:
- repo: https://github.com/astral-sh/uv-pre-commit
rev: 0.9.18
hooks:
- id: pip-compile
args: [requirements.in, -o, requirements.txt]Multiple Requirements Files
repos:
- repo: https://github.com/astral-sh/uv-pre-commit
rev: 0.9.18
hooks:
- id: pip-compile
name: pip-compile requirements.in
args: [requirements.in, -o, requirements.txt]
- id: pip-compile
name: pip-compile requirements-dev.in
args: [requirements-dev.in, -o, requirements-dev.txt]
files: ^requirements-dev\.(in|txt)$---
Tools and Scripts
Running Tools (uvx)
# One-off tool execution
uvx ruff check .
uvx black --check .
uvx mypy src/
# Specific version
uvx ruff@0.5.0 check .
# With dependencies
uvx --with mkdocs-material mkdocs build
# From different package
uvx --from httpie http https://api.example.comInstalling Tools Globally
# Install
uv tool install ruff
uv tool install "ruff==0.5.0"
uv tool install --python 3.12 mypy
# List installed
uv tool list
# Upgrade
uv tool upgrade ruff
uv tool upgrade --all
# Uninstall
uv tool uninstall ruff
# Add to PATH
uv tool update-shellScripts with Inline Dependencies (PEP 723)
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "requests<3",
# "rich",
# ]
# ///
import requests
from rich import print
response = requests.get("https://api.example.com")
print(response.json())# Make executable and run
chmod +x script.py
./script.py
# Or run directly
uv run script.py
# Add dependencies to script
uv add --script script.py pandas---
direnv Integration
Basic .envrc
# .envrc
if has uv; then
VIRTUAL_ENV="$(pwd)/.venv"
if [[ ! -d "$VIRTUAL_ENV" ]]; then
uv venv
fi
PATH_add "$VIRTUAL_ENV/bin"
export VIRTUAL_ENV
fiCustom Layout Function
Add to ~/.config/direnv/direnvrc:
layout_uv() {
if ! has uv; then
log_error "uv not found. Install from https://astral.sh/uv"
return 1
fi
VIRTUAL_ENV="$(pwd)/.venv"
if [[ ! -d "$VIRTUAL_ENV" ]]; then
uv venv
fi
PATH_add "$VIRTUAL_ENV/bin"
export VIRTUAL_ENV
}Usage in .envrc:
layout uv---
IDE Integration
VS Code
settings.json:
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
"python.terminal.activateEnvironment": true
}PyCharm
1. Open Project Settings > Python Interpreter 2. Add Interpreter > Add Local Interpreter 3. Select Existing > Navigate to .venv/bin/python
---
Environment Variables Reference
Core Settings
| Variable | Purpose | Example |
|---|---|---|
UV_CACHE_DIR | Cache directory | /tmp/.uv-cache |
UV_PYTHON | Default Python | 3.12 |
UV_PROJECT | Project directory | /path/to/project |
UV_CONFIG_FILE | Config file path | /path/to/uv.toml |
Index Configuration
| Variable | Purpose | Example |
|---|---|---|
UV_DEFAULT_INDEX | Default package index | https://pypi.org/simple |
UV_INDEX | Additional indexes | https://private.pypi.org |
UV_INDEX_{NAME}_USERNAME | Index username | user |
UV_INDEX_{NAME}_PASSWORD | Index password | pass |
Resolution Control
| Variable | Purpose | Example |
|---|---|---|
UV_FROZEN | Don't update lockfile | 1 |
UV_LOCKED | Assert lockfile unchanged | 1 |
UV_NO_DEV | Exclude dev dependencies | 1 |
UV_CONSTRAINT | Constraint files | constraints.txt |
Build Settings
| Variable | Purpose | Example |
|---|---|---|
UV_COMPILE_BYTECODE | Compile .pyc | 1 |
UV_LINK_MODE | Link mode | copy, hardlink, symlink |
UV_NO_BINARY | Build from source | 1 |
UV_NO_BUILD | Only use wheels | 1 |
Network Settings
| Variable | Purpose | Example |
|---|---|---|
UV_HTTP_TIMEOUT | HTTP timeout (seconds) | 30 |
UV_OFFLINE | Disable network | 1 |
UV_NATIVE_TLS | Use system TLS | 1 |
Python Management
| Variable | Purpose | Example |
|---|---|---|
UV_PYTHON_INSTALL_DIR | Python install location | /opt/python |
UV_NO_PYTHON_DOWNLOADS | Disable auto-download | 1 |
UV_MANAGED_PYTHON | Require managed Python | 1 |
---
Common Integration Patterns
Makefile
.PHONY: install test lint format
install:
uv sync --locked
test:
uv run pytest -v
lint:
uv run ruff check .
uv run mypy src/
format:
uv run ruff format .
uv run ruff check --fix .
build:
uv build
publish:
uv publishtox Alternative
# Run tests across Python versions
for py in 3.10 3.11 3.12; do
uv run --python $py pytest
doneDocker Compose Development
# docker-compose.yml
services:
app:
build: .
volumes:
- .:/app
- /app/.venv # Preserve container's venv
command: uv run python -m my_app
# docker-compose.override.yml (development)
services:
app:
develop:
watch:
- action: sync
path: .
target: /app
ignore:
- .venv/
- action: rebuild
path: ./pyproject.tomlDeployment Script
#!/bin/bash
set -e
# Production deployment
uv sync --locked --no-dev
uv run python -m my_app---
Troubleshooting Integrations
Docker Issues
| Issue | Solution |
|---|---|
| Cache mount failures | Set UV_LINK_MODE=copy |
| Slow builds | Use multi-stage builds with cache mounts |
| Large images | Use --no-cache or distroless base |
CI/CD Issues
| Issue | Solution |
|---|---|
| Lockfile changes | Use --locked flag |
| Cache bloat | Run uv cache prune --ci |
| Slow jobs | Enable caching in setup action |
Tool Issues
| Issue | Solution |
|---|---|
| Tool not on PATH | Run uv tool update-shell |
| Wrong tool version | Use uvx tool@version |
| Python version mismatch | Use --python flag |
uv Project Management Reference
Comprehensive guide to managing Python projects with uv.
Project Structure
Core Files
my-project/
├── pyproject.toml # Project definition (required)
├── uv.lock # Lock file (auto-generated)
├── .venv/ # Virtual environment (auto-created)
├── .python-version # Python version pin (optional)
├── README.md
└── src/
└── my_project/
├── __init__.py
└── main.pyFile Purposes
| File | Purpose | Version Control |
|---|---|---|
pyproject.toml | Project metadata, dependencies, configuration | Yes |
uv.lock | Exact resolved versions for reproducibility | Yes |
.venv/ | Virtual environment (auto-excluded) | No |
.python-version | Python version pin | Yes |
---
pyproject.toml Configuration
Minimal Configuration
[project]
name = "my-project"
version = "0.1.0"Complete Example
[project]
name = "my-project"
version = "0.1.0"
description = "My awesome Python project"
readme = "README.md"
license = { text = "MIT" }
authors = [
{ name = "Your Name", email = "you@example.com" }
]
keywords = ["python", "example"]
classifiers = [
"Development Status :: 3 - Alpha",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
]
requires-python = ">=3.11"
# Main dependencies
dependencies = [
"requests>=2.28",
"click>=8.0",
"pydantic>=2.0",
]
# Optional dependencies (extras)
[project.optional-dependencies]
api = ["fastapi>=0.100", "uvicorn>=0.23"]
database = ["sqlalchemy>=2.0", "alembic>=1.12"]
all = ["my-project[api,database]"]
# Entry points
[project.scripts]
my-cli = "my_project.cli:main"
[project.gui-scripts]
my-gui = "my_project.gui:main"
[project.entry-points."my_project.plugins"]
plugin-a = "my_project.plugins:PluginA"
# URLs
[project.urls]
Homepage = "https://github.com/user/my-project"
Documentation = "https://my-project.readthedocs.io"
Repository = "https://github.com/user/my-project"
# Build system
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
# Dependency groups (PEP 735)
[dependency-groups]
dev = ["pytest>=8", "ruff>=0.5", "mypy>=1.10"]
test = ["pytest-cov>=5", "pytest-asyncio>=0.23"]
docs = ["sphinx>=7", "myst-parser>=3"]
lint = ["ruff>=0.5", "mypy>=1.10", "pre-commit>=3"]
# UV-specific configuration
[tool.uv]
# Default groups to install
default-groups = ["dev"]
# Alternative dev dependencies (deprecated, use dependency-groups)
dev-dependencies = ["pytest", "ruff"]
# Constraint dependencies
constraint-dependencies = ["grpcio<1.65"]
# Override dependencies (force specific versions)
override-dependencies = ["werkzeug==2.3.0"]
# Exclude from resolution
exclude-dependencies = ["some-package"]
# Package indexes
[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[[tool.uv.index]]
name = "private"
url = "https://pypi.company.com/simple"
# Dependency sources
[tool.uv.sources]
# Git repository
my-lib = { git = "https://github.com/user/my-lib" }
my-lib-branch = { git = "https://github.com/user/my-lib", branch = "develop" }
my-lib-tag = { git = "https://github.com/user/my-lib", tag = "v1.0.0" }
my-lib-rev = { git = "https://github.com/user/my-lib", rev = "abc123" }
# Local path
local-pkg = { path = "./packages/local-pkg" }
local-editable = { path = "./packages/local-pkg", editable = true }
# Specific index
torch = { index = "pytorch" }
# URL
direct-pkg = { url = "https://example.com/package-1.0.0.whl" }
# Environment markers
[tool.uv.sources.jax]
marker = "sys_platform == 'linux'"
# Target environments for resolution
[tool.uv]
environments = [
"sys_platform == 'darwin'",
"sys_platform == 'linux'",
]
# Conflicts (mutually exclusive extras/groups)
[tool.uv]
conflicts = [
[
{ extra = "cpu" },
{ extra = "cuda" },
]
]
# pip interface settings (only for uv pip commands)
[tool.uv.pip]
index-url = "https://pypi.org/simple"---
Dependency Management
Adding Dependencies
# Add to project.dependencies
uv add requests
uv add "requests>=2.28"
uv add requests flask sqlalchemy
# Add development dependencies
uv add --dev pytest ruff mypy
# Add to specific group
uv add --group test pytest-cov
uv add --group lint ruff mypy
# Add optional dependency (extra)
uv add --optional api fastapi uvicorn
# Add from different sources
uv add "git+https://github.com/user/repo"
uv add "git+https://github.com/user/repo@v1.0.0"
uv add "../local-package"
uv add torch --index https://download.pytorch.org/whl/cpu
# Platform-specific dependency
uv add "jax; sys_platform == 'linux'"Removing Dependencies
uv remove requests
uv remove --dev pytest
uv remove --group test pytest-cov
uv remove --optional api fastapiUpdating Dependencies
# Upgrade all dependencies
uv lock --upgrade
# Upgrade specific package
uv lock --upgrade-package requests
# Change version constraint
uv add "requests>=2.30"---
Lock File Management
Lock File Behavior
The uv.lock file:
- Contains exact resolved versions for all platforms/Python versions
- Is human-readable TOML format
- Should be committed to version control
- Is managed by uv (don't edit manually)
Lock Commands
# Create/update lock file
uv lock
# Check if lock file is up-to-date
uv lock --check
# Upgrade all packages
uv lock --upgrade
# Upgrade specific package
uv lock --upgrade-package requests
uv lock --upgrade-package "requests==2.32.0"Lock File Freshness
Lock file is considered outdated when:
- Dependencies added/removed from pyproject.toml
- Version constraints changed to exclude locked version
Lock file remains valid when:
- New upstream versions released (explicit upgrade needed)
- Constraint changes still include locked version
---
Environment Synchronization
Basic Sync
# Sync environment (includes dev by default)
uv sync
# Use exact lockfile (CI/production)
uv sync --locked
# Don't update lockfile
uv sync --frozenControlling What's Installed
# Exclude development dependencies
uv sync --no-dev
# Only development dependencies
uv sync --only-dev
# Include specific group
uv sync --group test
uv sync --group test --group lint
# Exclude specific group
uv sync --no-group lint
# All groups
uv sync --all-groups
# No default groups
uv sync --no-default-groups
# Include extras (optional dependencies)
uv sync --extra api
uv sync --all-extras
# Only specific group (no project)
uv sync --only-group testPartial Installation (Docker/CI Optimization)
# Install dependencies without project
uv sync --no-install-project
# Skip specific packages
uv sync --no-install-package dev-only-lib
# Skip workspace members
uv sync --no-install-workspaceSync Options
# Remove extraneous packages (default)
uv sync --exact
# Keep extraneous packages
uv sync --inexact
# Non-editable install
uv sync --no-editable---
Running Commands
Basic Execution
# Run command in project environment
uv run python script.py
uv run pytest
uv run my-cli --help
# Run Python module
uv run -m my_module
# Arguments after command passed directly
uv run pytest -v --tb=shortExecution Options
# Use lockfile only (error if outdated)
uv run --locked python script.py
# Don't check environment freshness
uv run --frozen python script.py
# Don't sync environment
uv run --no-sync python script.py
# Include temporary dependency
uv run --with pandas python analyze.py
# Isolated environment
uv run --isolated python script.py
# Load environment file
uv run --env-file .env python app.py
# Include extras
uv run --all-extras python script.py
uv run --extra api python script.py---
Workspaces
Workspace Structure
workspace-root/
├── pyproject.toml # Workspace root
├── uv.lock # Single lockfile for entire workspace
├── packages/
│ ├── package-a/
│ │ ├── pyproject.toml
│ │ └── src/
│ └── package-b/
│ ├── pyproject.toml
│ └── src/
└── apps/
└── my-app/
├── pyproject.toml
└── src/Workspace Configuration
# workspace-root/pyproject.toml
[tool.uv.workspace]
members = ["packages/*", "apps/*"]
# Exclude patterns
exclude = ["packages/deprecated-*"]Workspace Commands
# Sync all workspace members
uv sync --all-packages
# Run in specific package
uv run --package package-a pytest
# Add dependency to workspace member
uv add --package package-a requests---
Dependency Groups (PEP 735)
Defining Groups
[dependency-groups]
dev = [
"pytest>=8",
"ruff>=0.5",
"mypy>=1.10",
]
test = [
"pytest-cov>=5",
"pytest-asyncio>=0.23",
]
docs = [
"sphinx>=7",
"myst-parser>=3",
]
all = [
{ include-group = "test" },
{ include-group = "docs" },
]
# Group with Python version constraint
[tool.uv.dependency-groups]
typing = { requires-python = ">=3.10" }Using Groups
# Default behavior (includes default-groups)
uv sync
# Include specific group
uv sync --group test
# Multiple groups
uv sync --group test --group docs
# Exclude group
uv sync --no-group lint
# All groups
uv sync --all-groups
# Only specific group
uv sync --only-group testDefault Groups
[tool.uv]
# Single group
default-groups = ["dev"]
# Multiple groups
default-groups = ["dev", "lint"]
# All groups
default-groups = "all"---
Optional Dependencies (Extras)
Defining Extras
[project.optional-dependencies]
api = ["fastapi>=0.100", "uvicorn>=0.23"]
database = ["sqlalchemy>=2.0", "alembic>=1.12"]
redis = ["redis>=5.0"]
all = ["my-project[api,database,redis]"]Using Extras
# Sync with extra
uv sync --extra api
# Multiple extras
uv sync --extra api --extra database
# All extras
uv sync --all-extras
# Run with extra
uv run --extra api python app.py---
Package Indexes
Configuring Indexes
# Default index (replaces PyPI)
[[tool.uv.index]]
url = "https://pypi.company.com/simple"
default = true
# Additional index
[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cpu"
# Explicit index (only for explicitly mapped packages)
[[tool.uv.index]]
name = "private"
url = "https://private.pypi.org/simple"
explicit = true
# Map package to index
[tool.uv.sources]
torch = { index = "pytorch" }
private-pkg = { index = "private" }Index Authentication
# Environment variable
UV_INDEX_PRIVATE_USERNAME=user
UV_INDEX_PRIVATE_PASSWORD=pass
# Or login
uv auth login https://private.pypi.org---
Constraints and Overrides
Constraint Dependencies
Limit versions without adding as dependencies:
[tool.uv]
constraint-dependencies = [
"grpcio<1.65",
"protobuf<5.0",
]Override Dependencies
Force specific versions (dangerous - use sparingly):
[tool.uv]
override-dependencies = [
"werkzeug==2.3.0",
]Build Constraints
Constrain build dependencies:
[tool.uv]
build-constraint-dependencies = [
"setuptools==60.0.0",
]---
Exporting Lock Files
Export Formats
# Requirements.txt format
uv export --format requirements-txt -o requirements.txt
# PEP 751 pylock.toml
uv export --format pylock.toml -o pylock.toml
# CycloneDX SBOM
uv export --format cyclonedx1.5 -o sbom.jsonExport Options
# Without hashes
uv export --format requirements-txt --no-hashes
# Without dev dependencies
uv export --no-dev
# With specific extras
uv export --extra api
# With all extras
uv export --all-extras---
Virtual and Non-Package Projects
Virtual Project (No Package)
For applications that won't be published:
[project]
name = "my-app"
version = "0.1.0"
[tool.uv]
package = false # Don't treat as installable packageUnmanaged Project
Opt out of uv management:
[tool.uv]
managed = false---
Best Practices
Version Control
# .gitignore
.venv/
__pycache__/
*.pyc
.pytest_cache/
.mypy_cache/
.ruff_cache/
dist/
*.egg-info/
# Don't ignore these:
# pyproject.toml
# uv.lock
# .python-versionDevelopment Workflow
1. Initial setup:
uv sync2. Add dependencies:
uv add requests
uv add --dev pytest3. Run code:
uv run python script.py
uv run pytest4. Update dependencies:
uv lock --upgrade-package requests5. Commit changes:
git add pyproject.toml uv.lock
git commit -m "Update dependencies"CI/CD
# Always use --locked in CI
uv sync --locked
# Prune cache after CI job
uv cache prune --ciDocker
# Install dependencies first (for caching)
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-install-project
# Then copy source
COPY . .
RUN uv sync --lockedFlask Patterns Reference
Common patterns and best practices for Flask web applications.
Application Factory
# app/__init__.py
from flask import Flask
def create_app(config_name: str = "default") -> Flask:
"""Application factory."""
app = Flask(__name__)
# Load config
app.config.from_object(config[config_name])
# Initialize extensions
db.init_app(app)
# Register blueprints
from app.main import main as main_blueprint
app.register_blueprint(main_blueprint)
from app.api import api as api_blueprint
app.register_blueprint(api_blueprint, url_prefix="/api")
return appBlueprints
# app/main/__init__.py
from flask import Blueprint
main = Blueprint("main", __name__)
from app.main import routes # noqa: E402, F401# app/main/routes.py
from flask import render_template
from app.main import main
@main.route("/")
def index():
return render_template("index.html")
@main.route("/about")
def about():
return render_template("about.html")API Patterns
JSON Responses
from flask import jsonify, request
@app.route("/api/items", methods=["GET"])
def get_items():
items = Item.query.all()
return jsonify([item.to_dict() for item in items])
@app.route("/api/items", methods=["POST"])
def create_item():
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
item = Item(**data)
db.session.add(item)
db.session.commit()
return jsonify(item.to_dict()), 201
@app.route("/api/items/<int:item_id>", methods=["GET"])
def get_item(item_id: int):
item = Item.query.get_or_404(item_id)
return jsonify(item.to_dict())Error Handling
from flask import jsonify
@app.errorhandler(404)
def not_found(error):
return jsonify({"error": "Not found"}), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return jsonify({"error": "Internal server error"}), 500Templates
Base Template
<!-- templates/base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock %} - MyApp</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
{% block styles %}{% endblock %}
</head>
<body>
<nav>
<a href="{{ url_for('main.index') }}">Home</a>
<a href="{{ url_for('main.about') }}">About</a>
</nav>
<main>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</main>
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
{% block scripts %}{% endblock %}
</body>
</html>Child Template
<!-- templates/index.html -->
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome</h1>
<p>Hello, {{ name }}!</p>
{% for item in items %}
<div class="item">
<h2>{{ item.title }}</h2>
<p>{{ item.description }}</p>
</div>
{% else %}
<p>No items found.</p>
{% endfor %}
{% endblock %}Forms with Flask-WTF
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length
class ContactForm(FlaskForm):
name = StringField("Name", validators=[DataRequired(), Length(max=100)])
message = TextAreaField("Message", validators=[DataRequired()])
submit = SubmitField("Send")@app.route("/contact", methods=["GET", "POST"])
def contact():
form = ContactForm()
if form.validate_on_submit():
# Process form
flash("Message sent!", "success")
return redirect(url_for("main.index"))
return render_template("contact.html", form=form)Database with Flask-SQLAlchemy
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
posts = db.relationship("Post", backref="author", lazy=True)
def to_dict(self) -> dict:
return {
"id": self.id,
"username": self.username,
"email": self.email,
}
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)Configuration
# config.py
import os
class Config:
SECRET_KEY = os.environ.get("SECRET_KEY") or "dev-key-change-in-prod"
SQLALCHEMY_TRACK_MODIFICATIONS = False
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "sqlite:///dev.db"
class ProductionConfig(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
config = {
"development": DevelopmentConfig,
"production": ProductionConfig,
"default": DevelopmentConfig,
}Testing
# tests/conftest.py
import pytest
from app import create_app, db
@pytest.fixture
def app():
app = create_app("testing")
with app.app_context():
db.create_all()
yield app
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
# tests/test_routes.py
def test_index(client):
response = client.get("/")
assert response.status_code == 200
def test_api_items(client):
response = client.get("/api/items")
assert response.status_code == 200
assert response.json == []Deployment
Gunicorn
# Install
uv add gunicorn
# Run
uv run gunicorn -w 4 -b 0.0.0.0:8000 "app:create_app()"Docker
FROM python:3.12-slim
WORKDIR /app
# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
# Copy project
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev
COPY . .
EXPOSE 8000
CMD ["uv", "run", "gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "app:create_app()"]uv Command Reference
Complete reference for uv (astral-sh/uv) Python package manager.
Installation
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# Update uv
uv self updateProject Management
# Initialize
uv init <name> # Create new project
uv init --lib <name> # Create library project
uv init --app <name> # Create application project
# Dependencies
uv add <package> # Add dependency
uv add <package>==1.0.0 # Add specific version
uv add <package>>=1.0,<2.0 # Add version range
uv add --dev <package> # Add dev dependency
uv add --optional <group> <pkg> # Add optional dependency
uv remove <package> # Remove dependency
# Sync & Lock
uv lock # Generate/update lockfile
uv sync # Sync environment with lockfile
uv sync --frozen # Sync without updating lock
uv sync --all-extras # Include all optional depsRunning Code
# Run commands in project environment
uv run python script.py # Run Python script
uv run pytest # Run pytest
uv run flask run # Run Flask
uv run <any-command> # Run any command
# Run with specific Python
uv run --python 3.12 script.pyTools (pipx replacement)
# Run tools ephemerally
uvx ruff check . # Run ruff without installing
uvx black . # Run black formatter
uvx --from package tool # Run tool from package
# Install tools globally
uv tool install ruff # Install tool
uv tool upgrade ruff # Upgrade tool
uv tool uninstall ruff # Remove tool
uv tool list # List installed toolsPython Version Management
# Install Python versions
uv python install 3.12 # Install specific version
uv python install 3.11 3.12 # Install multiple versions
uv python list # List available versions
uv python list --installed # List installed versions
# Pin version for project
uv python pin 3.12 # Creates .python-version file
# Create venv with specific version
uv venv --python 3.12Virtual Environments
# Create venv
uv venv # Create .venv
uv venv myenv # Create named venv
uv venv --python 3.12 # With specific Python
# Activate (standard way)
source .venv/bin/activate # Linux/macOS
.venv\Scripts\activate # Windowspip Interface (drop-in replacement)
# Install packages
uv pip install <package>
uv pip install -r requirements.txt
uv pip install -e . # Editable install
# Compile requirements
uv pip compile requirements.in -o requirements.txt
uv pip compile --universal # Platform-independent
# Sync environment
uv pip sync requirements.txt
# Other pip commands
uv pip list
uv pip show <package>
uv pip freeze
uv pip uninstall <package>Scripts with Inline Dependencies
# Add dependencies to script
uv add --script script.py requests pandas
# Run script (auto-installs deps)
uv run script.pyScript format:
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "requests>=2.31",
# "pandas>=2.0",
# ]
# ///
import requests
import pandas as pd
# ...Build & Publish
# Build package
uv build # Build sdist and wheel
uv build --sdist # Build source dist only
uv build --wheel # Build wheel only
# Publish to PyPI
uv publish # Publish to PyPI
uv publish --token <token> # With API tokenConfiguration
pyproject.toml
[project]
name = "my-package"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"flask>=3.0",
]
[project.optional-dependencies]
dev = ["pytest", "ruff", "mypy"]
[tool.uv]
dev-dependencies = [
"pytest>=8.0",
]Environment Variables
UV_CACHE_DIR # Cache directory location
UV_NO_CACHE # Disable cache
UV_PYTHON # Default Python version
UV_SYSTEM_PYTHON # Use system Python
UV_COMPILE_BYTECODE # Compile .pyc files#!/bin/bash
# Initialize a new Python project with modern tooling
# Usage: ./init-project.sh <project-name> [--flask]
set -e
PROJECT_NAME="${1:-my-project}"
INCLUDE_FLASK=false
# Parse arguments
for arg in "$@"; do
case $arg in
--flask)
INCLUDE_FLASK=true
shift
;;
esac
done
echo "🐍 Creating Python project: $PROJECT_NAME"
# Initialize with uv
uv init "$PROJECT_NAME"
cd "$PROJECT_NAME"
# Create directory structure
mkdir -p src/"${PROJECT_NAME//-/_}"
mkdir -p tests
mkdir -p scripts
# Create __init__.py
cat > src/"${PROJECT_NAME//-/_}"/__init__.py << 'EOF'
"""Package initialization."""
__version__ = "0.1.0"
EOF
# Create main module
cat > src/"${PROJECT_NAME//-/_}"/main.py << 'EOF'
"""Main module."""
def main() -> None:
"""Entry point."""
print("Hello from the project!")
if __name__ == "__main__":
main()
EOF
# Create test file
cat > tests/test_main.py << 'EOF'
"""Tests for main module."""
import pytest
def test_placeholder() -> None:
"""Placeholder test."""
assert True
EOF
# Add dev dependencies
uv add --dev pytest ruff mypy
# Add Flask if requested
if [ "$INCLUDE_FLASK" = true ]; then
echo "🌶️ Adding Flask..."
uv add flask
mkdir -p static/css static/js templates
# Create Flask app
cat > app.py << 'EOF'
"""Flask application."""
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index() -> str:
"""Home page."""
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
EOF
# Create base template
cat > templates/base.html << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}App{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<main>
{% block content %}{% endblock %}
</main>
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
</body>
</html>
EOF
# Create index template
cat > templates/index.html << 'EOF'
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome!</h1>
<p>Your Flask application is running.</p>
{% endblock %}
EOF
# Create empty CSS/JS
touch static/css/style.css
touch static/js/main.js
fi
# Sync dependencies
uv sync
echo "✅ Project created successfully!"
echo ""
echo "Next steps:"
echo " cd $PROJECT_NAME"
echo " uv run pytest # Run tests"
echo " uv run ruff check . # Check code"
if [ "$INCLUDE_FLASK" = true ]; then
echo " uv run flask run --debug # Start Flask server"
fi
Python Project Skill
Modern Python project development using uv package manager and Flask for web components.
Quick Start
New Project with uv
# Initialize new project
uv init my-project
cd my-project
# Add dependencies
uv add flask pytest ruff mypy
# Run application
uv run python app.py
# Run with Flask
uv run flask run --debugPackage Manager: uv
Use uv (astral-sh/uv) for all Python package management. It replaces pip, poetry, pyenv, and virtualenv.
Common Commands
# Project management
uv init <name> # Initialize project
uv add <package> # Add dependency
uv remove <package> # Remove dependency
uv sync # Sync dependencies from lockfile
uv lock # Generate lockfile
# Running
uv run <command> # Run in project environment
uv run python script.py # Run Python script
uv run pytest # Run tests
# Tools (like pipx)
uvx <tool> # Run tool in ephemeral env
uv tool install <tool> # Install tool globally
# Python versions
uv python install 3.12 # Install Python version
uv python pin 3.12 # Pin version for projectWeb Framework: Flask
Use Flask for web applications - lightweight WSGI micro-framework.
Minimal Flask App
# app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/data", methods=["GET", "POST"])
def api_data():
if request.method == "POST":
data = request.get_json()
return jsonify({"status": "ok", "received": data})
return jsonify({"message": "Hello, API!"})
if __name__ == "__main__":
app.run(debug=True)Flask Project Structure
my_flask_app/
├── app.py # Application entry
├── pyproject.toml # uv project config
├── static/ # CSS, JS, images
│ ├── css/
│ └── js/
├── templates/ # Jinja2 templates
│ ├── base.html
│ └── index.html
└── tests/
└── test_app.pyRun Flask
# Development
uv run flask run --debug
# With specific host/port
uv run flask run --host=0.0.0.0 --port=8080Project Configuration
pyproject.toml
[project]
name = "my-project"
version = "0.1.0"
description = "Project description"
requires-python = ">=3.11"
dependencies = [
"flask>=3.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.5",
"mypy>=1.10",
]
[tool.ruff]
line-length = 88
target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "I", "UP"]
[tool.mypy]
python_version = "3.11"
strict = true
[tool.pytest.ini_options]
testpaths = ["tests"]Code Quality
# Linting and formatting with ruff
uv run ruff check . # Check for issues
uv run ruff check . --fix # Auto-fix issues
uv run ruff format . # Format code
# Type checking
uv run mypy .
# Testing
uv run pytest
uv run pytest -v --cov=srcScripts
scripts/init-project.sh- Initialize new Python project with standard structurescripts/setup-flask.sh- Set up Flask application boilerplate
References
- See
references/uv-commands.mdfor complete uv reference - See
references/flask-patterns.mdfor Flask best practices
uv Python Version Management Reference
Comprehensive guide to managing Python versions with uv.
Overview
uv provides integrated Python version management:
- Automatic Python downloads when needed
- Multiple version installations
- Version pinning per project or globally
- Support for CPython, PyPy, GraalPy, and Pyodide
---
Installing Python
Basic Installation
# Install latest Python
uv python install
# Install specific version
uv python install 3.12
uv python install 3.12.5
# Install multiple versions
uv python install 3.11 3.12 3.13
# Install with default executables (python, python3)
uv python install 3.12 --defaultAlternative Implementations
# PyPy
uv python install pypy
uv python install pypy@3.10
# GraalPy
uv python install graalpy
# Specific implementation version
uv python install cpython@3.12Version Constraints
# Range constraint
uv python install ">=3.11,<3.13"
# Latest satisfying constraint
uv python install ">=3.10"Installation Options
# Reinstall existing versions
uv python install --reinstall
# Include preview releases
uv python install --preview---
Listing Python Versions
Basic Listing
# Show available and installed versions
uv python list
# Filter by version
uv python list 3.12
uv python list pypy
# Show only installed
uv python list --only-installedAdvanced Listing
# Include all patch versions
uv python list --all-versions
# Show downloads for all platforms
uv python list --all-platformsOutput Example
cpython-3.13.1-macos-aarch64-none # installed
cpython-3.12.8-macos-aarch64-none # installed
cpython-3.12.7-macos-aarch64-none # available
cpython-3.11.10-macos-aarch64-none # installed
pypy-3.10.14-macos-aarch64-none # available---
Version Pinning
Project-Level Pin
# Create .python-version in current directory
uv python pin 3.12
# Pin exact version
uv python pin 3.12.5
# Pin with resolved exact version
uv python pin 3.12 --resolvedGlobal Pin
# User-level default
uv python pin --global 3.12Pin File Format
.python-version:
3.12For multiple versions (.python-versions):
3.11
3.12
3.13pyproject.toml Constraint
[project]
requires-python = ">=3.11"---
Finding Python
Basic Find
# Find first available Python
uv python find
# Find specific version
uv python find 3.12
uv python find ">=3.11"Find Options
# Ignore virtual environments
uv python find --system
# Ignore project requirements
uv python find --no-projectDiscovery Order
1. Managed Python installations (UV_PYTHON_INSTALL_DIR) 2. PATH executables (python, python3, python3.x) 3. Windows registry / Microsoft Store (Windows only)
---
Version Selection
Command-Line Override
# Use specific version for any command
uv sync --python 3.12
uv run --python 3.11 python script.py
uv venv --python 3.12Environment Variable
# Set default Python
export UV_PYTHON=3.12Selection Priority
1. --python command-line argument 2. UV_PYTHON environment variable 3. .python-version file (searches up directory tree) 4. requires-python in pyproject.toml 5. First available Python
---
Version Request Formats
Standard Formats
| Format | Example | Description |
|---|---|---|
| Major | 3 | Any 3.x version |
| Minor | 3.12 | Any 3.12.x version |
| Patch | 3.12.5 | Exact version |
| Range | >=3.11,<3.13 | Version constraint |
| Implementation | cpython, pypy | Specific implementation |
| Combined | cpython@3.12 | Implementation + version |
| Path | /usr/bin/python3 | Executable path |
| Name | python3.12 | Executable name |
Special Variants
# Free-threaded Python (3.13+)
uv python install 3.13t
uv python install 3.13+freethreaded
# Debug build
uv python install 3.13d
uv python install 3.13+debug
# Force GIL-enabled (3.14+)
uv python install 3.14+gilPlatform-Specific
# Full specification
uv python install cpython-3.12.3-macos-aarch64-none
uv python install cpython-3.12.3-linux-x86_64-gnu---
Upgrading Python
Upgrade Command (Preview)
# Upgrade to latest patch version
uv python upgrade 3.12
# Upgrade all installed versions
uv python upgradeNote: Only supports patch upgrades (3.12.x -> 3.12.y), not minor upgrades.
Auto-Upgrade Virtual Environments (Preview)
# Enable with preview features
uv python install 3.12 --preview-features python-upgrade---
Uninstalling Python
# Remove specific version
uv python uninstall 3.11
# Remove multiple versions
uv python uninstall 3.11 3.12---
Configuration
Environment Variables
| Variable | Purpose |
|---|---|
UV_PYTHON | Default Python version |
UV_PYTHON_INSTALL_DIR | Python installation directory |
UV_PYTHON_PREFERENCE | Version selection preference |
UV_NO_PYTHON_DOWNLOADS | Disable automatic downloads |
UV_MANAGED_PYTHON | Require uv-managed Python |
Python Preference
Configure how uv selects Python:
# uv.toml or [tool.uv] in pyproject.toml
[tool.uv]
python-preference = "managed" # defaultOptions:
managed- Prefer uv-managed, fall back to systemonly-managed- Only use uv-managed versionssystem- Prefer system over managedonly-system- Only use system versions
Disable Auto-Download
# Command-line
uv sync --no-python-downloads
# Environment variable
export UV_NO_PYTHON_DOWNLOADS=1
# Configuration file
[tool.uv]
python-downloads = "manual"---
Supported Implementations
CPython (Default)
- Source: Astral's
python-build-standalone - Self-contained, portable, performant
- Aliases:
cpython,cp
PyPy
- Source: PyPy project official distributions
- JIT-compiled Python
- Aliases:
pypy,pp
GraalPy
- Source: GraalPy project distributions
- Aliases:
graalpy,gp
Pyodide
- WebAssembly Python
- Alias:
pyodide
---
Platform Support
Supported Platforms
| Platform | Architecture | Notes |
|---|---|---|
| macOS | x86_64, aarch64 | Rosetta 2 supports x86_64 on ARM |
| Linux | x86_64, aarch64 | glibc-based |
| Windows | x86_64, aarch64 | WoA emulation for x86_64 |
Transparent Emulation
On macOS (aarch64) with Rosetta 2:
- Both x86_64 and aarch64 binaries work
- uv can use either, packages must match architecture
On Windows (ARM) with WoA:
- x86_64 binaries work via emulation
- Same architectural consistency requirement
---
Windows Integration
Registry Integration
uv automatically registers managed Python in Windows registry (PEP 514):
- Enables discovery by
pylauncher - Enables discovery by other tools
Using py Launcher
py -V:Astral/CPython3.13.1---
Common Workflows
Multi-Version Testing
# Install multiple versions
uv python install 3.10 3.11 3.12 3.13
# Test against each
for v in 3.10 3.11 3.12 3.13; do
uv run --python $v pytest
doneProject with Specific Version
# Pin version
uv python pin 3.12
# Sync will use pinned version
uv sync
# Run uses pinned version
uv run python --versionIsolated Tool Execution
# Run tool with specific Python
uvx --python 3.11 ruff check .
# Install tool with specific Python
uv tool install --python 3.12 mypyCI/CD Configuration
# GitHub Actions
- uses: astral-sh/setup-uv@v7
with:
python-version: "3.12"
# Or use matrix
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: astral-sh/setup-uv@v7
with:
python-version: ${{ matrix.python-version }}---
Troubleshooting
Version Not Found
# Check available versions
uv python list --all-versions
# Check if installed
uv python list --only-installed
# Force download
uv python install 3.12Wrong Version Selected
# Check what's being used
uv python find
# Explicitly specify
uv run --python 3.12 python --version
# Check .python-version
cat .python-version
# Check pyproject.toml
grep requires-python pyproject.tomlVirtual Environment Issues
# Recreate with specific version
rm -rf .venv
uv venv --python 3.12
uv syncSystem Python Conflicts
# Use only managed Python
export UV_MANAGED_PYTHON=1
# Or configure
[tool.uv]
python-preference = "only-managed"