Python 编程 — 通用方法 是做什么的?
这是 Python 主参考技能文档。它记录了本项目中所有 Python 代码不可妥协的默认约定和“轻函数式”编程哲学。请先阅读本文,然后遵循链接的领域技能以获得更深入的指导。
核心技术栈
| 关注点 | 选择 |
|---|---|
| 包管理器与任务运行器 | uv |
| 打包清单 | 仅 pyproject.toml |
| 代码检查器/格式化工具 | ruff |
| 类型检查器 | ty |
| 数据处理库 | polars(非 pandas) |
| 后端框架 | FastAPI |
| 数据库 | PostgreSQL |
| ORM | SQLAlchemy(异步) |
| 迁移工具 | Alembic |
| 运行时模型 | asyncio — 始终异步 |
| 编程风格 | 轻函数式 |
包管理 — 始终使用 uv
切勿直接使用 pip、pip-tools、poetry 或 pipenv。
所有安装、运行和脚本操作均使用 uv 及其原生命令。
# 安装依赖
uv sync
# 添加依赖
uv add <package>
# 添加开发依赖
uv add --dev <package>
# 运行脚本或模块
uv run python script.py
uv run alembic upgrade head
uv run pytest
# 升级依赖
uv lock --upgrade
为获得可重现的构建,所有生产依赖应使用 == 锁定版本。
请勿使用 requirements.txt、requirements-dev.txt 或任何 requirements 目录来管理依赖。所有包元数据和依赖配置都应放在 pyproject.toml 中。
对于任何涉及包、工具或构建的操作,都使用 uv。切勿在本项目中直接运行 pip、pip install、python -m pip、poetry 或 pipenv。
有关完整的升级工作流程,请参阅 upgrade-dependencies 技能:
.github/skills/upgrade-dependencies/SKILL.md
有关库创建的具体指南,请参阅 .github/skills/python-library-creation/SKILL.md。
代码检查与格式化 — Astral 技术栈为强制要求
本仓库的 Python 项目必须使用 Astral 技术栈。ruff 是标准的代码检查器和格式化工具。
- 将
ruff添加为开发依赖:uv add --dev ruff - 使用
uv run ruff format格式化代码。 - 使用
uv run ruff check --fix运行代码检查并尽可能自动修复问题。 - 在项目脚本或 README 中记录这些命令。
ruff 是代码、测试和配置在格式化和样式一致性方面的唯一权威来源。
类型检查 — 首选 ty
类型注解是必需的。本仓库首选 ty 作为类型检查器。
- 将
ty添加为开发依赖:uv add --dev ty - 使用
uv run ty check运行类型检查 - 使用
uv run --with ty ty check验证工具链(如需比较行为)。
本仓库可能仍会实验其他检查器,如 mypy 或 pyrefly,但 ty 是首选的主检查器,并应在 CI 中强制执行。
数据处理 — Polars 与 DuckDB
本仓库在进程内数据工程中首选 polars,在 SQL 优先的分析和大型文件查询中首选 DuckDB。
-
当智能体扮演 Speedster 角色时使用 Polars:
- 由 Rust 驱动,单机上的多线程 DataFrame 处理。
- 最适合复杂的管道链、特征工程、连接、窗口函数和程序化转换。
- 优先考虑吞吐量和计算速度,具有更严格的模式与类型安全性。
- 非常适合模型预处理以及与 Python ML 工具的集成。
-
当智能体扮演 Librarian 角色时使用 DuckDB:
- 针对分析型 OLAP 查询优化的进程内 SQL 数据库。
- 以 SQL 为先的意图更适合将自然语言可靠地转换为代码。
- 在内存受限的工作负载下表现更佳:DuckDB 强制执行严格的内存限制,并可以安全地查询非常大的数据集。
- 理想用于零 ETL 直接通过 URL 查询 S3 或 Google Cloud 中的远程文件。
决策启发式
如果任务是:
- 探索新文件或云存储 → DuckDB
- 在直接文件扫描和 SQL 探索方面表现最佳。
- 过滤或排序大规模数据集 → Polars
- 在单节点上的原始过滤和加载速度方面通常占优。
- 协作或交接 → DuckDB
- SQL 对人类和智能体来说更易于维护和调试。
- 模型预处理 → Polars
- 与 Python ML 工具和模式安全管道的集成更好。
后端 — FastAPI
FastAPI 是唯一支持的后端框架。关键约定:
- 始终使用
async def定义路由处理器和依赖项。 - 对所有请求/响应模型使用 Pydantic v2 模型。
- 使用
Depends()声明依赖项 — 切勿在处理器内部访问全局状态。 - 返回类型化的响应模型;切勿从路由处理器返回原始字典。
- 路由位于独立的模块中;
main.py仅挂载路由器和配置中间件。
# ✅ 正确模式
@router.get("/items/{item_id}", response_model=ItemResponse)
async def get_item(item_id: int, db: AsyncSession = Depends(get_db)) -> ItemResponse:
return await item_service.get(db, item_id)
关于结构设计、测试、安全性和 OpenAPI 文档,请参考 FastAPI 领域技能文档:
.github/skills/python-fastapi-project-structuring/SKILL.md.github/skills/python-fastapi-routing-validation/SKILL.md.github/skills/python-fastapi-dependency-injection/SKILL.md.github/skills/python-fastapi-response-error-handling/SKILL.md.github/skills/python-fastapi-security-authentication/SKILL.md.github/skills/python-fastapi-security-attack-resistance/SKILL.md.github/skills/python-fastapi-api-testing/SKILL.md.github/skills/python-fastapi-openapi-documentation/SKILL.md
数据库 — PostgreSQL + SQLAlchemy(异步)
PostgreSQL 是唯一支持的数据库。SQLAlchemy 是 ORM。
- 始终使用异步引擎和会话(
AsyncEngine、AsyncSession)。 - 切勿在异步代码中调用同步的 SQLAlchemy API。
- 使用
sqlalchemy中的select()、insert()、update()、delete()— 而非原始 SQL 字符串。 - 使用
async with AsyncSession(engine) as session管理会话生命周期。 - 使用
DeclarativeBase定义模型;使用Mapped[T]类型化列注解(SQLAlchemy 2.x 风格)。
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
engine = create_async_engine("postgresql+asyncpg://...", echo=False)
class Base(DeclarativeBase):
pass
class Item(Base):
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
数据库迁移 — Alembic
Alembic 管理所有模式变更。切勿手动变更数据库模式。
关键规则:
- 迁移一旦应用于非本地环境,即 不可变。
- 每次迁移应尽可能具有 幂等性。
- 所有 Alembic 命令均应使用
uv run alembic。
uv run alembic revision --autogenerate -m "add_items_table"
uv run alembic upgrade head
uv run alembic history
uv run alembic current
有关完整的迁移编写规则和行级安全(RLS)执行,请参阅:
.github/skills/python-alembic-migrations/SKILL.md
有关基于本地迁移分支的变基操作,请参阅:
.github/skills/python-alembic-migration-rebase/SKILL.md
异步 — 始终使用
所有 I/O 操作 必须 是异步的。在请求路径中不应存在阻塞调用。
- 使用
asyncio.gather()并发执行独立的协程。 - 使用
asyncio.TaskGroup(Python 3.11+)处理结构化并发和错误传播。 - 使用
asyncio.Queue或asyncio.Semaphore实现背压和速率限制。 - 切勿调用
time.sleep()— 应使用await asyncio.sleep()。 - 切勿使用
requests— 应使用httpx.AsyncClient或aiohttp。
更深入的指导:
.github/skills/python-asyncio/asyncio-concurrent-web-requests/SKILL.md.github/skills/python-concurrent-processing/SKILL.md(CPU 密集型任务 →ProcessPoolExecutor+ asyncio 集成).github/skills/python-asyncio/asyncio-synchronization/SKILL.md
轻函数式编程风格
代码库采用“轻函数式”方法:在 能够降低复杂度、提升清晰度 的地方应用函数式技术,但不应为了理论纯粹性而强制执行。
我们执行的
| 技术 | 使用时机 |
|---|---|
| 纯函数 | 业务逻辑的默认选择。除非必要,否则不产生副作用。 |
| 不可变数据 | 对值对象使用冻结的 dataclass / Pydantic 模型。 |
| 高阶函数 | 在数据处理管道中,优先使用 map、filter、functools.reduce 而非命令式循环。 |
| 生成器 / 惰性序列 | 处理大型或流式数据集 — 避免在内存中构建完整的列表。 |
functools 工具 | lru_cache、cache、partial、wraps — 可自由使用。 |
| 函数组合 | 在数据转换管道中链接小而专注的函数。 |
| 描述性装饰器 | 将横切关注点(认证、缓存、重试)表达为装饰器。 |
我们不强制使用的
| 技术 | 除非明显有益,否则避免的原因 |
|---|---|
单子(Maybe、Either、Result) | 增加认知负担;建议改用异常 + 类型化返回值。 |
| Point-free 风格 | 降低大多数团队成员的代码可读性。 |
| 严格的全盘不可变性 | SQLAlchemy 模型和异步状态本质上是可变的 — 仅在必要时加以控制。 |
pymonad / returns 库 | 仅限选择性使用;未经团队同意,不得强加于共享代码。 |
# ✅ 轻函数式:由专注的纯函数组成的管道
from functools import reduce
def parse_items(raw: list[dict]) -> list[Item]:
return [Item(**r) for r in raw if r.get("active")]
def enrich(item: Item, overrides: dict) -> Item:
return item.model_copy(update=overrides.get(item.id, {}))
def process(raw: list[dict], overrides: dict) -> list[Item]:
return [enrich(item, overrides) for item in parse_items(raw)]
更深入的指导 — 整合与专门的函数式技能文档:
.github/skills/python-higher-order-functools/SKILL.md(map、filter、max/min、@cache、partial、reduce、@singledispatch).github/skills/python-lazy-evaluation-pipelines/SKILL.md(yield、yield from、生成器管道、map/filter/reduce).github/skills/python-immutable-data-design/SKILL.md(NamedTuple、冻结 dataclass、pyrsistent、上下文管理器).github/skills/python-functional-programming/python-decorator-design/SKILL.md.github/skills/python-functional-programming/python-functional-web-services/SKILL.md(FastAPI 函数式处理器).github/skills/python-functional-programming/python-toolz-composition/SKILL.md.github/skills/python-functional-programming/python-itertools-combinatorics/SKILL.md.github/skills/python-functional-programming/python-recursion-tco/SKILL.md.github/skills/python-functional-programming/python-pymonad-strict-evaluation/SKILL.md← 仅限选择性使用
通用代码约定
- 最低 Python 3.11+。使用现代语法:
match、TypeAlias、Self等。 - 所有内容都要有类型注解 — 函数签名、变量、返回类型。
- 无
Any,除非是与未类型化的第三方库集成的边界。 - 值对象优先使用
dataclass(frozen=True)或 PydanticBaseModel。 - 保持函数小巧且单一职责。如果一个函数需要注释来解释它 做什么(而不是 为什么),则应进行拆分。
- 避免全局可变状态。显式传递依赖项(通过构造函数或
Depends())。 - 使用
logging— 而非print。在应用启动时配置日志;切勿在库代码中调用basicConfig()。 完整的日志、追踪和配置指南请参见.github/skills/python-configuration-observability/SKILL.md。
技能地图
python/SKILL.md ← 你在这里(主参考)
│
├── 后端框架
│ ├── python-fastapi-project-structuring/SKILL.md
│ ├── python-fastapi-routing-validation/SKILL.md
│ ├── python-fastapi-dependency-injection/SKILL.md
│ ├── python-fastapi-response-error-handling/SKILL.md
│ ├── python-fastapi-security-authentication/SKILL.md
│ ├── python-fastapi-security-attack-resistance/SKILL.md
│ ├── python-fastapi-api-testing/SKILL.md
│ └── python-fastapi-openapi-documentation/SKILL.md
│
├── 数据库与迁移
│ ├── python-alembic-migrations/SKILL.md
│ └── python-alembic-migration-rebase/SKILL.md
│
├── 异步模式
│ ├── python-asyncio/asyncio-concurrent-web-requests/SKILL.md
│ └── python-asyncio/asyncio-synchronization/SKILL.md
│
├── 整合的核心技能
│ ├── python-configuration-observability/SKILL.md (配置 + 日志 + 追踪)
│ ├── python-data-structures-type-system/SKILL.md (集合 + 类型 + Pydantic)
│ ├── python-lazy-evaluation-pipelines/SKILL.md (生成器 + map/filter/reduce)
│ ├── python-higher-order-functools/SKILL.md (HOFs + cache + partial + singledispatch)
│ ├── python-immutable-data-design/SKILL.md (NamedTuple + 冻结 DC + 上下文管理器)
│ └── python-concurrent-processing/SKILL.md (ProcessPool + asyncio 集成)
│
├── 函数式编程(专门)
│ ├── python-functional-programming/python-decorator-design/SKILL.md
│ ├── python-functional-programming/python-functional-web-services/SKILL.md
│ ├── python-functional-programming/python-toolz-composition/SKILL.md
│ ├── python-functional-programming/python-itertools-combinatorics/SKILL.md
│ ├── python-functional-programming/python-recursion-tco/SKILL.md
│ └── python-functional-programming/python-pymonad-strict-evaluation/SKILL.md ← 选择性使用
│
├── 库创建
│ ├── python-library-creation/SKILL.md
│ └── python-project-setup/SKILL.md
│
├── Polars
│ ├── python-p…
[因篇幅限制截断]