uv-project-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

uv Project Setup

uv 项目搭建

Purpose

用途

Initialize and configure new Python projects with uv, creating standardized, reproducible project structures with proper dependency management, Python version pinning, and organized dependency groups for development, testing, and production use.
使用uv初始化并配置新的Python项目,创建标准化、可复现的项目结构,同时实现合理的依赖管理、Python版本固定,以及为开发、测试和生产环境划分有序的依赖组。

Quick Start

快速开始

Initialize a new project with a single command that creates all necessary files:
bash
undefined
使用一条命令初始化新项目,自动创建所有必要文件:
bash
undefined

Initialize project in current directory or new directory

Initialize project in current directory or new directory

uv init my-project cd my-project
uv init my-project cd my-project

Install dependencies in isolated environment

Install dependencies in isolated environment

uv sync
uv sync

Start developing

Start developing

uv run python main.py

This creates a complete project structure with `pyproject.toml`, `.python-version`, `.venv/`,
and a sample `main.py`. Everything is ready to add dependencies and start coding.
uv run python main.py

这会创建一个完整的项目结构,包含`pyproject.toml`、`.python-version`、`.venv/`以及示例文件`main.py`。此时已准备好添加依赖并开始编码。

Instructions

操作步骤

Step 1: Initialize Project Structure

步骤1:初始化项目结构

bash
undefined
bash
undefined

Create new project directory and initialize

Create new project directory and initialize

uv init my-project cd my-project
uv init my-project cd my-project

Or initialize in current directory

Or initialize in current directory

mkdir my-project && cd my-project uv init

This creates:
- `pyproject.toml` - Project metadata and dependencies configuration
- `.python-version` - Pinned Python version file
- `README.md` - Project documentation template
- `main.py` - Entry point script
- `.gitignore` - Git exclusion file
mkdir my-project && cd my-project uv init

这会创建以下文件:
- `pyproject.toml` - 项目元数据与依赖配置文件
- `.python-version` - Python版本固定文件
- `README.md` - 项目文档模板
- `main.py` - 项目入口脚本
- `.gitignore` - Git忽略规则文件

Step 2: Pin Python Version to Project

步骤2:为项目固定Python版本

bash
undefined
bash
undefined

Pin to specific Python version (creates .python-version)

Pin to specific Python version (creates .python-version)

uv python pin 3.12
uv python pin 3.12

Pin to minor version range

Pin to minor version range

uv python pin 3.12.3
uv python pin 3.12.3

Verify pinning worked

Verify pinning worked

cat .python-version

The `.python-version` file ensures all team members use the same Python version automatically
when working in the project directory.
cat .python-version

`.python-version`文件确保所有团队成员在项目目录中工作时,会自动使用相同的Python版本。

Step 3: Add Project Dependencies

步骤3:添加项目依赖

bash
undefined
bash
undefined

Add runtime dependencies

Add runtime dependencies

uv add requests httpx pandas
uv add requests httpx pandas

Add exact versions

Add exact versions

uv add "fastapi==0.104.0"
uv add "fastapi==0.104.0"

Add version ranges (recommended)

Add version ranges (recommended)

uv add "django>=4.2,<5.0"
uv add "django>=4.2,<5.0"

Add with extras

Add with extras

uv add "pandas[excel,plot]"

Use semantic versioning ranges to balance stability with flexibility. The `uv.lock` file
ensures reproducible installations across all environments.
uv add "pandas[excel,plot]"

使用语义化版本范围在稳定性与灵活性之间取得平衡。`uv.lock`文件确保所有环境中的依赖安装结果一致。

Step 4: Organize Dependencies with Groups

步骤4:使用依赖组管理依赖

toml
undefined
toml
undefined

In pyproject.toml, define development groups under [dependency-groups]

In pyproject.toml, define development groups under [dependency-groups]

[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", ]

Then sync specific groups:

```bash
[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

Install all groups

Install all groups

uv sync --all-groups
uv sync --all-groups

Install only specific groups

Install only specific groups

uv sync --group dev --group lint
uv sync --group dev --group lint

Install without dev groups (production)

Install without dev groups (production)

uv sync --no-dev
undefined
uv sync --no-dev
undefined

Step 5: Configure Tool Settings

步骤5:配置工具设置

Add uv-specific configuration to
pyproject.toml
under
[tool.uv]
:
toml
[tool.uv]
pyproject.toml
[tool.uv]
部分添加uv专属配置:
toml
[tool.uv]

Use custom virtual environment location

Use custom virtual environment location

project-environment = ".venv"

project-environment = ".venv"

Define conflicting extras that can't be used together

Define conflicting extras that can't be used together

conflicts = [ [{ extra = "cuda" }, { extra = "cpu" }], ]
conflicts = [ [{ extra = "cuda" }, { extra = "cpu" }], ]

Support multiple platform-specific environments

Support multiple platform-specific environments

environments = [ "sys_platform == 'darwin'", "sys_platform == 'linux'", "sys_platform == 'win32'", ]
undefined
environments = [ "sys_platform == 'darwin'", "sys_platform == 'linux'", "sys_platform == 'win32'", ]
undefined

Step 6: Set Up Optional Dependencies (Extras)

步骤6:配置可选依赖(Extras)

For published packages, define extras that users can install:
toml
[project]
name = "my-package"
version = "0.1.0"
dependencies = ["httpx>=0.27.0"]

[project.optional-dependencies]
对于要发布的包,定义用户可选择安装的可选依赖:
toml
[project]
name = "my-package"
version = "0.1.0"
dependencies = ["httpx>=0.27.0"]

[project.optional-dependencies]

Extras for optional functionality

Extras for optional functionality

excel = ["openpyxl>=3.0.0"] plot = ["matplotlib>=3.5.0"]
excel = ["openpyxl>=3.0.0"] plot = ["matplotlib>=3.5.0"]

Meta-extra for everything

Meta-extra for everything

all = ["openpyxl>=3.0.0", "matplotlib>=3.5.0"]
[project.scripts]
all = ["openpyxl>=3.0.0", "matplotlib>=3.5.0"]
[project.scripts]

CLI entry points

CLI entry points

my-cli = "my_package.cli:main" dev-server = "my_package.server:run"

Users can then install your package with:

```bash
my-cli = "my_package.cli:main" dev-server = "my_package.server:run"

用户随后可以通过以下方式安装你的包:

```bash

Install with specific extras

Install with specific extras

pip install my-package[excel,plot]
pip install my-package[excel,plot]

Install with all extras

Install with all extras

pip install my-package[all]
undefined
pip install my-package[all]
undefined

Step 7: Test Project Setup

步骤7:测试项目配置

Verify the project is properly configured:
bash
undefined
验证项目是否配置正确:
bash
undefined

View dependency tree

View dependency tree

uv tree
uv tree

Run your project

Run your project

uv run python main.py
uv run python main.py

Create and activate environment manually (optional)

Create and activate environment manually (optional)

source .venv/bin/activate # Unix .venv\Scripts\activate # Windows
undefined
source .venv/bin/activate # Unix .venv\Scripts\activate # Windows
undefined

Examples

示例

Example 1: Web Development Project Setup

示例1:Web开发项目搭建

bash
undefined
bash
undefined

Initialize project

Initialize project

uv init my-api cd my-api
uv init my-api cd my-api

Pin Python version

Pin Python version

uv python pin 3.12
uv python pin 3.12

Add web framework and utilities

Add web framework and utilities

uv add fastapi uvicorn sqlalchemy pydantic
uv add fastapi uvicorn sqlalchemy pydantic

Add development dependencies

Add development dependencies

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

Verify setup

Verify setup

uv tree uv run pytest --collect-only
undefined
uv tree uv run pytest --collect-only
undefined

Example 2: Data Science Project

示例2:数据科学项目

bash
undefined
bash
undefined

Create data science project

Create data science project

uv init data-analysis cd data-analysis
uv init data-analysis cd data-analysis

Pin to Python 3.12

Pin to Python 3.12

uv python pin 3.12
uv python pin 3.12

Add data science stack

Add data science stack

uv add "pandas>=2.2.0" "numpy>=1.26.0" "scikit-learn>=1.3.0"
uv add "pandas>=2.2.0" "numpy>=1.26.0" "scikit-learn>=1.3.0"

Add Jupyter and visualization

Add Jupyter and visualization

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

Add development tools

Add development tools

uv add --group dev pytest jupyter-contrib-nbextensions
uv add --group dev pytest jupyter-contrib-nbextensions

Organize into pyproject.toml groups

Organize into pyproject.toml groups


**pyproject.toml:**
```toml
[project]
name = "data-analysis"
version = "0.1.0"
description = "Data analysis pipeline"
requires-python = ">=3.12"
dependencies = [
    "pandas>=2.2.0",
    "numpy>=1.26.0",
    "scikit-learn>=1.3.0",
    "matplotlib>=3.5.0",
]

[dependency-groups]
jupyter = ["jupyter>=1.0.0"]
dev = ["pytest>=8.0.0", "black>=23.0.0"]

**pyproject.toml:**
```toml
[project]
name = "data-analysis"
version = "0.1.0"
description = "Data analysis pipeline"
requires-python = ">=3.12"
dependencies = [
    "pandas>=2.2.0",
    "numpy>=1.26.0",
    "scikit-learn>=1.3.0",
    "matplotlib>=3.5.0",
]

[dependency-groups]
jupyter = ["jupyter>=1.0.0"]
dev = ["pytest>=8.0.0", "black>=23.0.0"]

Example 3: Library Project with Extras

示例3:包含可选依赖的库项目

bash
undefined
bash
undefined

Initialize library project

Initialize library project

uv init my-library cd my-library
uv init my-library cd my-library

Core dependencies only

Core dependencies only

uv add "requests>=2.31.0" "click>=8.1.0"
uv add "requests>=2.31.0" "click>=8.1.0"

Add testing framework

Add testing framework

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

Add linting/formatting

Add linting/formatting

uv add --group lint ruff mypy black
uv add --group lint ruff mypy black

Add documentation

Add documentation

uv add --group artifacts mkdocs mkdocs-material
uv add --group artifacts mkdocs mkdocs-material

Add optional features

Add optional features

uv add --group async aiohttp asyncio-contextmanager uv add --group database sqlalchemy psycopg2-binary

**pyproject.toml setup with extras:**
```toml
[project]
name = "my-library"
version = "0.1.0"
dependencies = ["requests>=2.31.0", "click>=8.1.0"]

[project.optional-dependencies]
async = ["aiohttp>=3.8.0"]
database = ["sqlalchemy>=2.0.0", "psycopg2-binary>=2.9.0"]
all = ["aiohttp>=3.8.0", "sqlalchemy>=2.0.0", "psycopg2-binary>=2.9.0"]

[dependency-groups]
dev = ["pytest>=8.0.0"]
lint = ["ruff>=0.1.0", "mypy>=1.7.0"]
docs = ["mkdocs>=1.5.0"]
uv add --group async aiohttp asyncio-contextmanager uv add --group database sqlalchemy psycopg2-binary

**pyproject.toml setup with extras:**
```toml
[project]
name = "my-library"
version = "0.1.0"
dependencies = ["requests>=2.31.0", "click>=8.1.0"]

[project.optional-dependencies]
async = ["aiohttp>=3.8.0"]
database = ["sqlalchemy>=2.0.0", "psycopg2-binary>=2.9.0"]
all = ["aiohttp>=3.8.0", "sqlalchemy>=2.0.0", "psycopg2-binary>=2.9.0"]

[dependency-groups]
dev = ["pytest>=8.0.0"]
lint = ["ruff>=0.1.0", "mypy>=1.7.0"]
docs = ["mkdocs>=1.5.0"]

Example 4: Configure Alternative Package Sources

示例4:配置替代包源

toml
undefined
toml
undefined

In pyproject.toml - use git repository for package

In pyproject.toml - use git repository for package

[tool.uv.sources]
[tool.uv.sources]

Get package from git tag

Get package from git tag

httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }

Install local package in editable mode (for monorepos)

Install local package in editable mode (for monorepos)

local-lib = { path = "../local-lib", editable = true }
local-lib = { path = "../local-lib", editable = true }

Use specific PyPI index for package

Use specific PyPI index for package

torch = { index = "pytorch" }
torch = { index = "pytorch" }

Define custom index

Define custom index

[[tool.uv.index]] name = "pytorch" url = "https://download.pytorch.org/whl/cu118" explicit = true # Only use for torch package above

Then add the package:
```bash
uv add torch
uv sync
[[tool.uv.index]] name = "pytorch" url = "https://download.pytorch.org/whl/cu118" explicit = true # Only use for torch package above

然后添加包:
```bash
uv add torch
uv sync

Example 5: Create Script with Inline Dependencies

示例5:创建包含内联依赖的脚本

python
#!/usr/bin/env -S uv run
python
#!/usr/bin/env -S uv run

/// script

/// script

requires-python = ">=3.12"

requires-python = ">=3.12"

dependencies = [

dependencies = [

"httpx>=0.27",

"httpx>=0.27",

"rich>=13.0",

"rich>=13.0",

]

]

///

///

import httpx from rich import print
def main(): response = httpx.get("https://api.github.com") print(response.json())
if name == "main": main()

Make executable and run:
```bash
chmod +x script.py
./script.py
import httpx from rich import print
def main(): response = httpx.get("https://api.github.com") print(response.json())
if name == "main": main()

设置可执行权限并运行:
```bash
chmod +x script.py
./script.py

Or run directly

Or run directly

uv run script.py
undefined
uv run script.py
undefined

Example 6: Multi-Platform Project

示例6:跨平台项目

toml
[project]
name = "cross-platform-app"
version = "0.1.0"
dependencies = [
    "click>=8.1.0",
    "pathlib-plus>=1.0.0",
]

[tool.uv]
toml
[project]
name = "cross-platform-app"
version = "0.1.0"
dependencies = [
    "click>=8.1.0",
    "pathlib-plus>=1.0.0",
]

[tool.uv]

Support multiple operating systems with different dependencies

Support multiple operating systems with different dependencies

environments = [ "sys_platform == 'darwin'", "sys_platform == 'linux'", "sys_platform == 'win32'", ]
[tool.uv.sources]
environments = [ "sys_platform == 'darwin'", "sys_platform == 'linux'", "sys_platform == 'win32'", ]
[tool.uv.sources]

Platform-specific wheels via environment markers

Platform-specific wheels via environment markers

[tool.uv.sources.pywin32] version = "306" markers = "sys_platform == 'win32'"
undefined
[tool.uv.sources.pywin32] version = "306" markers = "sys_platform == 'win32'"
undefined

Common Pitfalls and Solutions

常见陷阱与解决方案

Pitfall 1: Forgetting to Pin Python Version

陷阱1:忘记固定Python版本

Problem: Team members using different Python versions locally.
Solution:
bash
undefined
问题: 团队成员本地使用不同的Python版本。
解决方案:
bash
undefined

Always pin Python version early in project

Always pin Python version early in project

uv python pin 3.12
uv python pin 3.12

Commit .python-version to repository

Commit .python-version to repository

git add .python-version
undefined
git add .python-version
undefined

Pitfall 2: Adding Dependencies to Wrong Group

陷阱2:将依赖添加到错误的组

Problem: Development tools ending up in production installs.
Solution:
bash
undefined
问题: 开发工具被包含到生产环境安装包中。
解决方案:
bash
undefined

Wrong: adds to main dependencies

Wrong: adds to main dependencies

uv add pytest
uv add pytest

Correct: adds to dev group

Correct: adds to dev group

uv add --dev pytest uv add --group lint ruff
uv add --dev pytest uv add --group lint ruff

Then install only production deps

Then install only production deps

uv sync --no-dev
undefined
uv sync --no-dev
undefined

Pitfall 3: Not Committing Lock File

陷阱3:未提交锁文件

Problem: Different environments have different package versions.
Solution:
bash
undefined
问题: 不同环境中的包版本不一致。
解决方案:
bash
undefined

Always commit uv.lock to version control

Always commit uv.lock to version control

git add uv.lock git commit -m "Update dependencies"
git add uv.lock git commit -m "Update dependencies"

Use --frozen in CI to catch sync issues

Use --frozen in CI to catch sync issues

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

Pitfall 4: Missing Build System

陷阱4:缺少构建系统配置

Problem: Package won't build/install properly.
Solution:
toml
undefined
问题: 包无法正确构建或安装。
解决方案:
toml
undefined

Ensure build-system is defined in pyproject.toml

Ensure build-system is defined in pyproject.toml

[build-system] requires = ["hatchling"] build-backend = "hatchling.build"
[build-system] requires = ["hatchling"] build-backend = "hatchling.build"

Or use setuptools

Or use setuptools

requires = ["setuptools>=45", "wheel"] build-backend = "setuptools.build_meta"
undefined
requires = ["setuptools>=45", "wheel"] build-backend = "setuptools.build_meta"
undefined

Pitfall 5: Conflicting Dependency Groups

陷阱5:依赖组冲突

Problem: Incompatible packages can be installed together.
Solution:
toml
[tool.uv]
问题: 不兼容的包被同时安装。
解决方案:
toml
[tool.uv]

Prevent conflicting extras from being used together

Prevent conflicting extras from being used together

conflicts = [ [{ extra = "cuda" }, { extra = "cpu" }], ]
conflicts = [ [{ extra = "cuda" }, { extra = "cpu" }], ]

In dependency-groups, don't mix conflicting versions

In dependency-groups, don't mix conflicting versions

[dependency-groups]
[dependency-groups]

Keep compatible versions together

Keep compatible versions together

ml-cpu = ["torch-cpu>=2.0"] ml-gpu = ["torch-gpu>=2.0"]
undefined
ml-cpu = ["torch-cpu>=2.0"] ml-gpu = ["torch-gpu>=2.0"]
undefined

See Also

相关链接

  • uv-dependency-management - Managing dependencies, versions, and extras
  • uv-python-version-management - Installing and discovering Python versions
  • uv-ci-cd-integration - Setting up CI/CD pipelines with uv
  • uv-tool-management - Running and managing CLI tools with uvx
  • uv Documentation - Official uv reference
  • uv-dependency-management - 管理依赖、版本与可选依赖
  • uv-python-version-management - 安装与发现Python版本
  • uv-ci-cd-integration - 搭建基于uv的CI/CD流水线
  • uv-tool-management - 使用uvx运行与管理CLI工具
  • uv Documentation - uv官方文档