uv-dependency-management

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

uv Dependency Management

uv 依赖管理

Purpose

用途

Master dependency management with uv, including adding/removing packages, version constraints, dependency groups for development and production, lock files, and resolving version conflicts.
掌握使用uv进行依赖管理的方法,包括添加/移除包、版本约束、开发与生产环境的依赖分组、锁定文件以及解决版本冲突。

Quick Start

快速开始

Add a dependency and see it in your lock file:
bash
undefined
添加一个依赖项并在锁定文件中查看:
bash
undefined

Add a package with version constraint

Add a package with version constraint

uv add "requests>=2.31.0"
uv add "requests>=2.31.0"

View your dependency tree

View your dependency tree

uv tree
uv tree

Update all dependencies to latest compatible versions

Update all dependencies to latest compatible versions

uv lock --upgrade

Your `pyproject.toml` is automatically updated, and `uv.lock` ensures reproducible installs.
uv lock --upgrade

你的`pyproject.toml`会自动更新,`uv.lock`确保安装的可复现性。

Instructions

操作步骤

Step 1: Understand Dependency Scopes

步骤1:了解依赖范围

uv manages three types of dependencies:
Main Dependencies (project requirements)
toml
[project]
dependencies = [
    "fastapi>=0.104.0",
    "sqlalchemy>=2.0.0",
]
Optional Dependencies (extras for features)
toml
[project.optional-dependencies]
database = ["psycopg2-binary>=2.9.0"]
aws = ["boto3>=1.34.0"]
Development Groups (dev-only tools)
toml
[dependency-groups]
dev = ["pytest>=8.0.0", "black>=23.0.0"]
test = ["pytest-cov>=4.1.0"]
lint = ["ruff>=0.1.0", "mypy>=1.7.0"]
uv管理三种类型的依赖项:
主依赖项(项目核心需求)
toml
[project]
dependencies = [
    "fastapi>=0.104.0",
    "sqlalchemy>=2.0.0",
]
可选依赖项(功能扩展)
toml
[project.optional-dependencies]
database = ["psycopg2-binary>=2.9.0"]
aws = ["boto3>=1.34.0"]
开发分组(仅开发环境使用的工具)
toml
[dependency-groups]
dev = ["pytest>=8.0.0", "black>=23.0.0"]
test = ["pytest-cov>=4.1.0"]
lint = ["ruff>=0.1.0", "mypy>=1.7.0"]

Step 2: Add Dependencies

步骤2:添加依赖项

Add to main project:
bash
uv add requests httpx
uv add "fastapi>=0.104.0"
uv add "django>=4.2,<5.0"
Add to specific group:
bash
uv add --dev pytest                    # Add to 'dev' group
uv add --group test pytest-cov        # Add to 'test' group
uv add --group lint ruff mypy         # Add to 'lint' group
Add with extras:
bash
uv add "pandas[excel,plot]"
uv add --dev "pytest[cov]"
添加到主项目:
bash
uv add requests httpx
uv add "fastapi>=0.104.0"
uv add "django>=4.2,<5.0"
添加到指定分组:
bash
uv add --dev pytest                    # Add to 'dev' group
uv add --group test pytest-cov        # Add to 'test' group
uv add --group lint ruff mypy         # Add to 'lint' group
带扩展功能添加:
bash
uv add "pandas[excel,plot]"
uv add --dev "pytest[cov]"

Step 3: Use Version Constraints

步骤3:使用版本约束

Common patterns (semantic versioning):
bash
uv add "requests"                   # Latest
uv add "requests>=2.31.0"          # Minimum version
uv add "requests>=2.31.0,<3.0.0"   # Range (major bump)
uv add "requests~=2.31.0"          # Compatible release (~= 2.31.x)
uv add "requests==2.31.0"          # Exact version (production)
Recommended approach:
  • Development:
    >=
    (flexible, want latest)
  • Production:
    >=X,<Y
    (range, tested with that version)
  • Stable packages:
    ~=
    (compatible releases)
常见语义化版本模式:
bash
uv add "requests"                   # Latest
uv add "requests>=2.31.0"          # Minimum version
uv add "requests>=2.31.0,<3.0.0"   # Range (major bump)
uv add "requests~=2.31.0"          # Compatible release (~= 2.31.x)
uv add "requests==2.31.0"          # Exact version (production)
推荐实践:
  • 开发环境:
    >=
    (灵活适配最新版本)
  • 生产环境:
    >=X,<Y
    (限定范围,已测试版本)
  • 稳定包:
    ~=
    (兼容更新)

Step 4: Remove and Update Dependencies

步骤4:移除与更新依赖项

Remove a package:
bash
uv remove requests
uv remove pytest black              # Remove multiple
Update to specific version:
bash
uv add "requests@2.32.0"
Update all dependencies:
bash
uv sync --upgrade                   # Update and sync
uv lock --upgrade                   # Just update lock file
移除包:
bash
uv remove requests
uv remove pytest black              # Remove multiple
更新到指定版本:
bash
uv add "requests@2.32.0"
更新所有依赖项:
bash
uv sync --upgrade                   # Update and sync
uv lock --upgrade                   # Just update lock file

Step 5: Organize with Dependency Groups

步骤5:使用依赖分组进行管理

Define logical groupings in
pyproject.toml
:
toml
[dependency-groups]
dev = [
    "pytest>=8.0.0",
    "pytest-cov>=4.1.0",
    "black>=23.0.0",
]
lint = [
    "ruff>=0.1.0",
    "mypy>=1.7.0",
    "pylint>=3.0.0",
]
docs = [
    "mkdocs>=1.5.0",
    "mkdocs-material>=9.0.0",
]
Install specific groups:
bash
uv sync --group dev --group lint    # Install groups
uv sync --all-groups                # Install everything
uv sync --no-dev                    # Only main deps (production)
pyproject.toml
中定义逻辑分组:
toml
[dependency-groups]
dev = [
    "pytest>=8.0.0",
    "pytest-cov>=4.1.0",
    "black>=23.0.0",
]
lint = [
    "ruff>=0.1.0",
    "mypy>=1.7.0",
    "pylint>=3.0.0",
]
docs = [
    "mkdocs>=1.5.0",
    "mkdocs-material>=9.0.0",
]
安装指定分组:
bash
uv sync --group dev --group lint    # Install groups
uv sync --all-groups                # Install everything
uv sync --no-dev                    # Only main deps (production)

Step 6: Understand Lock Files

步骤6:理解锁定文件

Lock file (
uv.lock
):
  • Records exact versions of all dependencies
  • Ensures reproducible installs across machines
  • Should be committed to version control
  • Automatically updated when you change
    pyproject.toml
Workflow:
bash
undefined
锁定文件(
uv.lock
):
  • 记录所有依赖项的精确版本
  • 确保跨机器的可复现安装
  • 应提交到版本控制系统
  • 修改
    pyproject.toml
    时会自动更新
工作流:
bash
undefined

After changing pyproject.toml

After changing pyproject.toml

uv sync # Installs from lock or creates new lock
uv sync # Installs from lock or creates new lock

To explicitly update lock file

To explicitly update lock file

uv lock --upgrade # Update all to latest compatible
uv lock --upgrade # Update all to latest compatible

In CI/CD (use frozen to prevent surprises)

In CI/CD (use frozen to prevent surprises)

uv sync --frozen # Fails if lock is out of sync
undefined
uv sync --frozen # Fails if lock is out of sync
undefined

Step 7: Handle Dependency Conflicts

步骤7:处理依赖冲突

Problem: Two packages need incompatible versions of same library
Solution 1: Check if newer versions are compatible
bash
uv add "package-a"
uv add "package-b"   # Might fail with version conflict
**问题:**两个包需要同一库的不兼容版本
解决方案1:检查新版本是否兼容
bash
uv add "package-a"
uv add "package-b"   # Might fail with version conflict

Try adding with different constraints

Try adding with different constraints

uv add "package-a>=1.0,<2.0" uv add "package-b>=2.0,<3.0"

**Solution 2: Use separate dependency groups**
```toml
[dependency-groups]
ml-cpu = ["torch-cpu>=2.0"]
ml-gpu = ["torch-gpu>=2.0"]
bash
undefined
uv add "package-a>=1.0,<2.0" uv add "package-b>=2.0,<3.0"

**解决方案2:使用独立的依赖分组**
```toml
[dependency-groups]
ml-cpu = ["torch-cpu>=2.0"]
ml-gpu = ["torch-gpu>=2.0"]
bash
undefined

Install one group at a time

Install one group at a time

uv sync --group ml-cpu

**Solution 3: Investigate and pick winning version**
```bash
uv sync --group ml-cpu

**解决方案3:排查并选择合适版本**
```bash

See what's needed

See what's needed

uv add --dry-run "package-a" "package-b"
uv add --dry-run "package-a" "package-b"

One might need updating

One might need updating

uv add "package-a>=2.0" uv add "package-b>=3.0"
undefined
uv add "package-a>=2.0" uv add "package-b>=3.0"
undefined

Examples

示例

Example 1: Web API Project Setup

示例1:Web API项目搭建

bash
undefined
bash
undefined

Initialize and add web dependencies

Initialize and add web dependencies

uv init my-api cd my-api uv add fastapi uvicorn sqlalchemy pydantic
uv init my-api cd my-api uv add fastapi uvicorn sqlalchemy pydantic

Add development tools

Add development tools

uv add --group dev pytest pytest-asyncio uv add --group lint ruff mypy black
uv add --group dev pytest pytest-asyncio uv add --group lint ruff mypy black

Verify setup

Verify setup

uv tree

**Resulting pyproject.toml:**
```toml
[project]
name = "my-api"
version = "0.1.0"
dependencies = [
    "fastapi>=0.104.0",
    "uvicorn>=0.24.0",
    "sqlalchemy>=2.0.0",
    "pydantic>=2.5.0",
]

[dependency-groups]
dev = ["pytest>=8.0.0", "pytest-asyncio>=0.21.0"]
lint = ["ruff>=0.1.0", "mypy>=1.7.0", "black>=23.0.0"]
uv tree

**最终的pyproject.toml:**
```toml
[project]
name = "my-api"
version = "0.1.0"
dependencies = [
    "fastapi>=0.104.0",
    "uvicorn>=0.24.0",
    "sqlalchemy>=2.0.0",
    "pydantic>=2.5.0",
]

[dependency-groups]
dev = ["pytest>=8.0.0", "pytest-asyncio>=0.21.0"]
lint = ["ruff>=0.1.0", "mypy>=1.7.0", "black>=23.0.0"]

Example 2: Library with Optional Features

示例2:带可选功能的库

bash
undefined
bash
undefined

Create library with core deps

Create library with core deps

uv init my-library uv add "click>=8.1.0"
uv init my-library uv add "click>=8.1.0"

Add optional features as extras

Add optional features as extras

uv add --group excel "openpyxl>=3.0.0" uv add --group database "sqlalchemy>=2.0.0" uv add --group async "aiohttp>=3.8.0"
uv add --group excel "openpyxl>=3.0.0" uv add --group database "sqlalchemy>=2.0.0" uv add --group async "aiohttp>=3.8.0"

Setup development tools

Setup development tools

uv add --dev pytest
undefined
uv add --dev pytest
undefined

Example 3: Resolving Version Conflicts

示例3:解决版本冲突

bash
undefined
bash
undefined

Trying to add packages with conflicting requirements

Trying to add packages with conflicting requirements

uv add package-a # Works fine uv add package-b # Fails - needs different version of shared lib
uv add package-a # Works fine uv add package-b # Fails - needs different version of shared lib

View what's going on

View what's going on

uv add --dry-run package-b
uv add --dry-run package-b

Try different constraints

Try different constraints

uv add "package-a>=1.0,<1.5" uv add "package-b>=2.0,<2.5"
uv add "package-a>=1.0,<1.5" uv add "package-b>=2.0,<2.5"

Check if it works

Check if it works

uv tree
undefined
uv tree
undefined

Example 4: Data Science Project

示例4:数据科学项目

bash
undefined
bash
undefined

Create project

Create project

uv init data-pipeline cd data-pipeline
uv init data-pipeline cd data-pipeline

Data science core

Data science core

uv add pandas numpy scikit-learn
uv add pandas numpy scikit-learn

Analysis tools

Analysis tools

uv add jupyter matplotlib seaborn plotly
uv add jupyter matplotlib seaborn plotly

Development

Development

uv add --group dev pytest pytest-cov
uv add --group dev pytest pytest-cov

Final tree

Final tree

uv tree
undefined
uv tree
undefined

Example 5: Update Strategy for Production

示例5:生产环境更新策略

bash
undefined
bash
undefined

Initial setup with compatible ranges

Initial setup with compatible ranges

uv add "requests>=2.31.0,<3.0.0" uv add "fastapi>=0.104.0,<1.0.0"
uv add "requests>=2.31.0,<3.0.0" uv add "fastapi>=0.104.0,<1.0.0"

After testing on latest patch

After testing on latest patch

uv add "requests@2.31.3" uv add "fastapi@0.104.1"
uv add "requests@2.31.3" uv add "fastapi@0.104.1"

Lock file is frozen for production

Lock file is frozen for production

git add uv.lock git commit -m "Pin exact versions for production"
git add uv.lock git commit -m "Pin exact versions for production"

CI/CD uses frozen lock

CI/CD uses frozen lock

uv sync --frozen
undefined
uv sync --frozen
undefined

Example 6: Monorepo with Path Dependencies

示例6:包含路径依赖的单体仓库

bash
undefined
bash
undefined

Main project

Main project

uv init main-app cd main-app
uv init main-app cd main-app

Add local packages (editable)

Add local packages (editable)

uv add --editable ../shared-lib uv add --editable ../utils-lib
uv add --editable ../shared-lib uv add --editable ../utils-lib

Now imports work from both packages

Now imports work from both packages

undefined
undefined

Requirements

要求

  • uv installed (install:
    curl -LsSf https://astral.sh/uv/install.sh | sh
    )
  • Understanding of PEP 508 version specifiers (recommended)
  • Project with pyproject.toml (created by
    uv init
    )
  • Python 3.8+ available
  • 已安装uv(安装命令:
    curl -LsSf https://astral.sh/uv/install.sh | sh
  • 了解PEP 508版本规范(推荐)
  • 项目包含pyproject.toml(可通过
    uv init
    创建)
  • **Python 3.8+**可用

See Also

相关链接

  • uv-project-setup - Initial project creation
  • uv-python-version-management - Managing Python versions
  • uv-troubleshooting - Resolving dependency issues
  • uv Documentation - Official guide
  • uv-project-setup - 初始项目创建
  • uv-python-version-management - Python版本管理
  • uv-troubleshooting - 依赖问题排查
  • uv Documentation - 官方指南