uv Tutorial:Quickly Get Started with the Next-Gen Python Toolchain

uv, a high-performance Python manager in Rust. This tutorial guides installation, configuration, and demonstrates core commands for version management, dependency handling, environment activation, and script execution.


Foreword

The Python ecosystem is constantly evolving, and so are the tools that help developers efficiently manage their projects. This article will take an in-depth look at uv, an innovative tool появившийся from Astral (the creators of the Ruff linter), designed to revolutionize Python package and environment management. For developers seeking an efficient, integrated alternative to some functionalities of pip, venv, virtualenv, pip-tools, and even pyenv, uv is worth considering.

uv is written in Rust, and one of its core design goals is extreme speed. However, speed is not its only highlight. uv aims to provide a comprehensive, unified solution for many common Python development tasks.

Core Design Philosophy of uv

  1. Extreme Performance: The use of Rust allows uv to exhibit remarkable speed in operations such as dependency resolution, package downloading, and installation, significantly outperforming existing Python tools.
  2. Unified Experience: uv integrates functionalities like Python version management, project initialization, dependency management, script execution, tool running, and package building and publishing into a single command-line interface, reducing the overhead of switching between tools.
  3. Modern Python Practices: It emphasizes project configuration via pyproject.toml and introduces a robust, cross-platform uv.lock lock file mechanism.
  4. Backward Compatibility (with caveats): The uv pip subcommand offers an interface highly compatible with common pip and pip-tools workflows, facilitating user migration, though it's not intended to be an exact clone of pip.

Installing and Configuring uv

Before diving into its features, let's first cover how to install and configure uv.

Installing uv

uv offers multiple installation methods to suit different operating systems and preferences.

  • Standalone Installation Script (Recommended): This is the most direct and cross-platform consistent installation method.

    • macOS and Linux: Open your terminal and run either of the following commands:
    # Using curl
    curl -LsSf https://astral.sh/uv/install.sh | sh
    # Or, if curl is not available on your system, use wget
    # wget -qO- https://astral.sh/uv/install.sh | sh

    To install a specific version (e.g., 0.7.5):

    curl -LsSf https://astral.sh/uv/0.7.5/install.sh | sh
    • Windows (PowerShell): Open PowerShell and run:
     powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

    To install a specific version (e.g., 0.7.5):

    powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/0.7.5/install.ps1 | iex"

    By default, uv is installed to the user's bin directory (e.g., ~/.local/bin), and the installation script usually tries to add this directory to your PATH automatically. You can customize the installation path by setting the UV_INSTALL_DIR environment variable, or prevent the script from modifying shell configuration files with INSTALLER_NO_MODIFY_PATH=1.

  • Via PyPI (using pipx or pip): It's recommended to install uv into an isolated environment using pipx:

    pipx install uv

    Alternatively, use pip (not recommended for global installation):

    pip install uv

    Note: If a pre-compiled wheel is not available for your platform, pip will attempt to build uv from source, which requires a Rust toolchain.

  • Other Package Managers:

    • Homebrew (macOS):
    brew install uv
    • WinGet (Windows):
    winget install --id=astral-sh.uv -e
    • Scoop (Windows):
    scoop install main/uv
    • Cargo (requires Rust environment):
    cargo install --git https://github.com/astral-sh/uv uv
  • Docker Images: uv provides official Docker images, e.g., ghcr.io/astral-sh/uv:latest or specific versions like ghcr.io/astral-sh/uv:0.7.5.

After installation, verify it by running uv --version or uv self version.

Updating uv

  • If installed via the standalone script:
    uv self update
    # uv self update <version> # To update to a specific version
  • If installed via other package managers, use their respective update commands (e.g., pipx upgrade uv).

Shell Autocompletion

Enabling shell autocompletion for uv and uvx commands can significantly improve efficiency. For example, for Bash:

echo 'eval "$(uv generate-shell-completion bash)"' >> ~/.bashrc
echo 'eval "$(uvx --generate-shell-completion bash)"' >> ~/.bashrc
# For Zsh, Fish, PowerShell, etc., refer to the official documentation for the corresponding commands

After completing these steps, restart your shell or reload the configuration file.

Configuring uv

uv's behavior can be configured in several ways, with the following order of precedence (highest to lowest):

  1. Command-line arguments.
  2. Environment variables: Prefixed with UV_, e.g., UV_INDEX_URL.
  3. Project-level configuration files:
    • The [tool.uv] table in the pyproject.toml file in the project root.
    • A uv.toml file in the project root (takes precedence over [tool.uv] in pyproject.toml if both exist in the same directory).
  4. User-level configuration file: e.g., ~/.config/uv/uv.toml (Linux/macOS).
  5. System-level configuration file: e.g., /etc/uv/uv.toml.

User-level and system-level configurations must use the uv.toml format. Configurations are merged, with project-level taking precedence over user-level, and user-level over system-level.

  • Disable configuration discovery: Use the --no-config command-line argument.
  • Specify a particular configuration file: Use --config-file /path/to/my-uv.toml.
  • .env file loading (for uv run): uv run can load environment variables from .env files via --env-file or UV_ENV_FILE.

In-depth Look at uv's Core Features

1. Python Version Management (uv python ...)

uv's management of Python interpreters themselves is a standout feature.

  • Managed vs. System Python: uv can discover and use existing Python installations on the system ("system Python"). It can also download and install Python versions itself ("managed Python").
  • Python Distribution Sources: uv relies on Astral's python-build-standalone project for pre-compiled CPython binaries and fetches PyPy from its official project.
  • On-demand Installation and Version Requesting: The --python flag allows requesting specific Python versions in most uv commands. Supported formats are very flexible. If a requested version is not available locally, uv will download and install it by default.
  • .python-version File Integration: uv supports .python-version files for declaring default Python versions for projects or globally. The uv python pin command easily creates these files.
    uv python pin 3.12 # Creates .python-version in the current directory
    uv python pin --global 3.11 # Creates a global .python-version file
  • Executable Installation (Preview): uv python install 3.12 --preview can install executables like python3.12 into the user's path.

2. Project and Workspace Management

uv's project management centers around pyproject.toml and introduces the concept of Workspaces.

  • Project Initialization (uv init): Quickly creates new projects adhering to modern Python project structures.
    uv init my_app # Creates an application project
    uv init --lib my_library # Creates a library project
  • Dependency Declaration: Declared in pyproject.toml's [project.dependencies], [project.optional-dependencies] (extras), and [dependency-groups] (PEP 735, e.g., dev group). [tool.uv.sources] allows specifying alternative sources for specific dependencies.
    uv add requests
    uv add --dev pytest
  • uv.lock – Universal Lock File: uv lock generates uv.lock, a cross-platform lock file recording exact resolved dependency versions for all environments.
  • Automatic Locking and Syncing: uv run and uv sync commands automatically check and update uv.lock and the .venv virtual environment before execution.
    uv sync
    uv lock --upgrade # Upgrades all packages and updates the lock file
  • Workspaces ([tool.uv.workspace]): Allows managing multiple related Python packages as a single unit, sharing a single uv.lock.

3. Script Execution (uv run)

  • PEP 723 Inline Metadata: For standalone Python scripts, uv run supports declaring dependencies and Python version requirements directly in the script file header using special comment blocks.
    # /// script
    # requires-python = ">=3.10"
    # dependencies = ["requests"]
    # ///
    import requests
    # ...
    Use uv add --script my_script.py requests to automatically add metadata.
  • Ephemeral Environments: When running scripts with inline metadata, uv automatically creates a temporary, isolated environment.
  • Shebang Support: #!/usr/bin/env -S uv run --script.

4. Tool Execution and Installation (uvx, uv tool ...)

  • uvx <tool_name>: Executes tools in a temporary, isolated environment without permanent installation.
    uvx ruff check .
  • uv tool install <package_name>: Installs tools into the user's bin directory, making them globally available.
    uv tool install black ruff
  • Version and Source Control: uvx ruff@0.3.0 or uvx --from 'ruff==0.3.0'.

5. pip-Compatible Interface (uv pip ...)

Provided for users accustomed to pip workflows.

  • Environment Creation (uv venv):

    uv venv .venv --python 3.11
  • Environment Activation (uv venv):

    Virtual environments created by uv (e.g., .venv) are standard and thus activated the same way as those created by venv or virtualenv.

    • macOS/Linux (Bash/Zsh):
      source .venv/bin/activate
    • Windows (PowerShell):
      .\.venv\Scripts\Activate.ps1
    • Windows (cmd.exe):
      .\.venv\Scripts\activate.bat

    After activation, the shell prompt will change, and subsequent python and pip commands will operate within this environment. Use deactivate to exit.

    Note: Many uv commands (like uv run, uv sync) automatically detect and use .venv without manual activation.

  • Package Installation and Uninstallation:

    # Assuming .venv is activated
    uv pip install django
    uv pip uninstall django
  • Dependency Compilation (uv pip compile):

    uv pip compile requirements.in -o requirements.txt
  • Environment Syncing (uv pip sync):

    uv pip sync requirements.txt # Accurately syncs the environment

6. Efficient Dependency Resolution and Caching

  • PubGrub Resolver: uv uses pubgrub-rs for dependency resolution.
  • Universal Resolution: uv lock performs universal resolution by default, creating a uv.lock that considers all platforms and Python versions.
  • Aggressive Caching: Caches downloaded wheels, built sdists, Git clones, etc.
    uv cache dir # View cache directory
    uv cache clean # Clean all cache
    uv cache prune --ci # Optimize cache for CI

7. Building and Publishing

  • uv build: Calls the project-defined build backend to build sdists and wheels.
    uv build # Builds sdist and wheel to dist/
  • uv publish: Uploads built distributions to a package index.
    uv publish dist/*

More

For more information and advanced usage of uv, please refer to the official uv documentation.