Astral uv & Modern Python Tooling Master Cheat Sheet
A definitive production CLI cheat sheet and transition runbook for Astral uv, the ultra-fast Rust-powered Python package manager. Master instant virtual environments, universal cross-platform lockfiles (uv.lock), automated multi-version Python runtime management, and high-speed Docker layer caching.
1. The Rust Revolution in Python: uv Architecture & Performance Advantages
pip for package installation, virtualenv for environments, pyenv for Python interpreter versions, pipx for standalone CLI applications, and poetry or pip-tools for dependency resolution and lockfiles.
Astral's uv consolidates all of these responsibilities into a single, cohesive binary written in Rust. By utilizing copy-on-write (reflinks) on modern filesystems, parallel PubGrub SAT dependency resolution, global wheel caching, and optimized HTTP/2 network transport, uv executes dependency installations and environment creations 10x to 100x faster than legacy tooling.
The following table summarizes how uv unifies the Python ecosystem:# Standalone installer for Linux and macOS (No Python dependency required)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Standalone installer for Windows (PowerShell)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# Alternatively, install via Homebrew on macOS
brew install uv
# Verify installation and active Rust engine version
uv --versionInstalls the self-contained uv binary without requiring an existing Python runtime.
| Legacy Tool | Astral uv Successor | Performance Multiplier | Consolidated Feature | Copy |
|---|---|---|---|---|
| pip install | uv pip install / uv add | 10x - 100x faster | Parallel wheel downloading, SAT-solving, and global symlink/reflink cache | |
| python -m venv | uv venv | 80x faster (~0.01s) | Instant virtual environment provisioning using filesystem reflinks | |
| pyenv install | uv python install | Native cross-platform | Downloads standalone pre-built CPython and PyPy runtimes automatically | |
| pipx run | uvx / uv tool run | Zero-latency ephemeral cache | Executes any PyPI CLI tool without permanent global installation | |
| pip-compile / poetry | uv lock / uv sync | Near-instant resolution | Generates cross-platform deterministic universal uv.lock files |
2. Virtual Environments & uv pip Drop-In Compatibility
requirements.txt files, uv provides a fully drop-in compatible sub-interface: uv pip.
This allows immediate 10x-100x acceleration without changing deployment scripts, Dockerfiles, or CI/CD pipelines.
Key capabilities:
- uv venv creates a complete, activated virtual environment in approximately 10 milliseconds.
- uv pip compile parses loose requirements.in declarations and solves an exact, hash-pinned requirements.txt manifest in fractions of a second.
- uv pip sync synchronizes your environment to match requirements.txt exactly, automatically uninstalling untracked orphaned packages.# 1. Create a modern virtual environment with Python 3.12 in ~12 milliseconds
uv venv --python 3.12 .venv
# 2. Activate the virtual environment (Standard command)
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# 3. Fast installation of complex multi-gigabyte data science wheels
uv pip install fastapi uvicorn "pydantic>=2.0" torch
# 4. Compile unpinned requirements.in into an exact deterministic lockfile
uv pip compile requirements.in -o requirements.txt
# 5. Strict synchronization: uninstalls any extra package not in requirements.txt
uv pip sync requirements.txtReplaces legacy virtualenv and pip commands with drop-in, multi-threaded Rust equivalents.
| Task | Legacy Command | Modern uv Equivalent | Operational Benefit | Copy |
|---|---|---|---|---|
| Create venv | python3 -m venv .venv | uv venv | Creates environment in ~0.01s via hardlinks/reflinks | |
| Install packages | pip install -r reqs.txt | uv pip install -r reqs.txt | Parallel HTTP/2 wheel downloads with global deduplication | |
| Compile lockfile | pip-compile requirements.in | uv pip compile requirements.in | Resolves SAT constraints across thousands of packages in under 1 second | |
| Prune orphaned deps | pip-sync requirements.txt | uv pip sync requirements.txt | Guarantees identical environment across staging and production | |
| List tree | pip list | uv pip tree | Visualizes complete dependency graph and nested transitive requirements |
3. Automated Python Runtime Management (No pyenv Required)
pyenv, alongside complex C-compiler toolchains to build Python from source.
uv introduces native, first-class Python runtime management:
- uv automatically downloads and manages pre-built, optimized standalone CPython and PyPy binaries directly from the official Python Software Foundation.
- It automatically detects project requirements from .python-version files or requires-python fields in pyproject.toml.
- If a project requires Python 3.11 and you only have Python 3.13 installed, running uv run or uv venv will silently download and use Python 3.11 on demand without user intervention.# List all available Python interpreters (Local and Remote)
uv python list
# Download and install specific CPython versions
uv python install 3.11 3.12 3.13
# Install PyPy for high-throughput JIT workloads
uv python install pypy@3.10
# Pin the current repository to a specific Python version (Creates .python-version)
uv python pin 3.12
# Run an ad-hoc command against an explicit Python version without installing it globally
uv run --python 3.10 -c "import sys; print(sys.version)"Installs and switches Python interpreter versions instantly without compiling from source.
| uv Command | Target Scope | Resolution Mechanism | Practical Example | Copy |
|---|---|---|---|---|
| uv python install <ver> | Global System | Downloads pre-compiled standalone CPython release | uv python install 3.13 | |
| uv python list | Inspection | Displays installed, active, and downloadable interpreters | uv python list --all | |
| uv python pin <ver> | Project Directory | Writes .python-version file locking project interpreter | uv python pin 3.12 | |
| uv python find | Environment | Prints exact filesystem path to currently resolved Python binary | uv python find 3.11 | |
| uv python uninstall <ver> | Global Storage | Removes cached interpreter to reclaim disk storage | uv python uninstall 3.9 |
4. Modern Project Lifecycle: pyproject.toml, uv lock & uv sync
pyproject.toml (PEP 517 / 518 / 621) and a universal uv.lock file.
Unlike traditional lockfiles that are platform-dependent (requiring separate locks for macOS ARM64 and Linux x86_64), uv.lock is universal:
- A single uv.lock resolves all dependency combinations across operating systems, architectures, and Python versions simultaneously.
- uv add and uv remove automatically update both pyproject.toml and uv.lock.
- uv run executes scripts within the project environment automatically, ensuring you never forget to activate your virtualenv.# 1. Initialize a new modern Python application project
uv init my-service
cd my-service
# 2. Add dependencies (Updates pyproject.toml and resolves uv.lock automatically)
uv add fastapi "uvicorn[standard]" httpx
# 3. Add development-only dependencies (e.g. testing and linting tools)
uv add --dev pytest ruff mypy
# 4. Execute application inside the synchronized virtualenv (Zero manual activation)
uv run uvicorn main:app --reload
# 5. In CI/CD pipelines: install exact dependencies strictly matching lockfile
uv sync --frozen --no-devFull project lifecycle workflow from initialization and dependency addition to CI lockfile enforcement.
| uv Project Command | Target File | Operational Action | Production Best Practice | Copy |
|---|---|---|---|---|
| uv init | pyproject.toml | Scaffolds clean PEP 621 project template | Use --app for services or --lib for reusable packages | |
| uv add <pkg> | pyproject.toml + uv.lock | Resolves dependency, updates lockfile, installs wheel | Specify semver ranges (e.g. "pydantic>=2.5") | |
| uv add --dev <pkg> | pyproject.toml [dev] | Adds package to separate development dependency group | Keep test and lint tooling out of production images | |
| uv remove <pkg> | pyproject.toml + uv.lock | Uninstalls package and purges unused transitive dependencies | Prevents dependency bloat across project milestones | |
| uv sync --frozen | Environment Sync | Installs lockfile without checking for remote updates | Mandatory flag in production Dockerfiles and CI runners | |
| uv lock --upgrade | uv.lock | Re-evaluates latest compatible package versions from PyPI | Run regularly to ingest security patches and bug fixes |
5. Standalone Tools (uvx), Ephemeral Scripts & Multi-Stage Docker Caching
uv run script.py will automatically provision a temporary isolated environment, install the dependencies, execute the script, and clean up.
Standalone CLI Tools (uvx):
The uvx command (shorthand for uv tool run) executes any tool from PyPI (such as Ruff, Black, HTTPie, or yt-dlp) in an isolated ephemeral sandbox without polluting your global system packages.
High-Speed Multi-Stage Docker Builds:
By leveraging uv's standalone binary and BuildKit cache mounts (--mount=type=cache,target=/root/.cache/uv), container build times can drop from minutes to sub-second cached rebuilds.# Save the following as 'scrape.py':
cat << 'EOF' > scrape.py
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "requests",
# "beautifulsoup4",
# ]
# ///
import requests
from bs4 import BeautifulSoup
resp = requests.get("https://example.com")
soup = BeautifulSoup(resp.text, "html.parser")
print("Page Title:", soup.title.string)
EOF
# Execute script with automatic on-the-fly dependency provisioning:
uv run scrape.pyExecutes standalone scripts declaring self-contained dependencies via PEP 723 metadata.
# syntax=docker/dockerfile:1
FROM python:3.12-slim-bookworm AS builder
# Install uv from official standalone image
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
WORKDIR /app
# Enable bytecode compilation and use system environment in container
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy
# 1. Cache dependency installation separately from application code
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --frozen --no-install-project --no-dev
# 2. Copy application source and finalize sync
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --frozen --no-dev
# Final production stage
FROM python:3.12-slim-bookworm
WORKDIR /app
COPY --from=builder /app /app
ENV PATH="/app/.venv/bin:$PATH"
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]Production Dockerfile achieving sub-second cached rebuilds using uv BuildKit cache mounts.
| Feature / Task | Command Syntax | Execution Sandbox | Key Operational Benefit | Copy |
|---|---|---|---|---|
| Run ephemeral tool | uvx ruff check . | Isolated temporary cache | Never pollutes system environment; always uses latest version | |
| Install persistent tool | uv tool install ruff | Dedicated isolated venv in ~/.local | Exposes binary directly on $PATH like pipx | |
| Self-contained script | uv run script.py | On-the-fly ephemeral venv | Reads inline PEP 723 metadata; fully portable across machines | |
| Compile bytecode | UV_COMPILE_BYTECODE=1 | Build-time flag | Pre-compiles .pyc files for faster container cold-start boot times |
Related Free Online Tools
Put these techniques into practice immediately with our privacy-first browser utilities:
Convert Docker commands into Compose services for multi-stage uv Python containers.
Validate and inspect API response payloads, pyproject configs, and lockfile exports.
Schedule automated uv script runs, sync pipelines, and background maintenance jobs.