Python Code Style & Documentation 是一个关于 Python 代码风格与文档规范的技能,目标是让代码库更易维护、更利于协作。它强调一致的代码风格和清晰的文档。
一、适用场景 该技能适用于以下情况:为新项目设置 linting 和格式化;编写或审查 docstring;建立团队编码标准;配置 ruff、mypy 或 pyright;审查代码风格一致性;创建项目文档。
二、核心概念
- 自动化格式化:让工具处理格式化争议,一次配置、自动强制执行。
- 一致命名:遵循 PEP 8 约定,使用有意义、描述性的名称。
- 文档即代码:docstring 应与其描述的代码同步维护。
- 类型注解:现代 Python 代码应为所有公开 API 添加类型提示。
三、快速开始 安装现代工具链:
pip install ruff mypy
然后在 pyproject.toml 中配置:
[tool.ruff] line-length = 120 target-version = "py312" # 根据项目最低 Python 版本调整
[tool.mypy] strict = true
四、基础模式 模式 1:现代 Python 工具链。使用 ruff 作为集成的 linter 和格式化工具,它用一个快速工具替代 flake8、isort 和 black。配置示例:
[tool.ruff] line-length = 120 target-version = "py312"
[tool.ruff.lint] select = ["E", "W", "F", "I", "B", "C4", "UP", "SIM"] ignore = ["E501"]
[tool.ruff.format] quote-style = "double" indent-style = "space"
运行方式:
ruff check --fix . # lint 并自动修复 ruff format . # 格式化代码
模式 2:类型检查配置。为生产代码配置严格类型检查:
[tool.mypy] python_version = "3.12" strict = true warn_return_any = true warn_unused_ignores = true disallow_untyped_defs = true disallow_incomplete_defs = true
[[tool.mypy.overrides]] module = "tests.*" disallow_untyped_defs = false
也可使用 pyright 获得更快的检查:
[tool.pyright] pythonVersion = "3.12" typeCheckingMode = "strict"
模式 3:命名约定。遵循 PEP 8,强调清晰而非简短。文件与模块使用描述性的 snake_case,如 user_repository.py、order_processing.py、http_client.py,避免缩写如 usr_repo.py。类使用 PascalCase,如 UserRepository、HTTPClientFactory(缩写保持大写)。函数和变量使用 snake_case,如 def get_user_by_email(email: str) -> User | None。模块级常量使用 SCREAMING_SNAKE_CASE,如 MAX_RETRY_ATTEMPTS、DEFAULT_TIMEOUT_SECONDS、API_BASE_URL。
模式 4:导入组织。按标准库、第三方、本地分组,顺序一致:
import os from collections.abc import Callable from typing import Any
import httpx from pydantic import BaseModel from sqlalchemy import Column
from myproject.models import User from myproject.services import UserService
优先使用绝对导入,避免相对导入:
from myproject.utils import retry_decorator # 推荐 from ..utils import retry_decorator # 避免
五、进阶模式 模式 5:Google 风格 docstring。为所有公开类、方法和函数编写 docstring。简单函数:
def get_user(user_id: str) -> User: """Retrieve a user by their unique identifier.""" ...
复杂函数使用 Args、Returns、Raises、Example 段落,例如 process_batch(items, max_workers=4, on_progress=None) 的 docstring 中说明各参数、返回值 BatchResult、可能抛出的 ValueError 和 ProcessingError,并给出示例。类 docstring 说明类用途、Attributes 和 Example,init 也应有 docstring。
模式 6:行宽与格式化。为现代显示器设置行宽 120 字符,同时保持可读性。函数参数过长时逐行换行;链式方法调用用括号包裹并清晰换行;长字符串通过相邻字符串拼接分行。
模式 7:项目文档。README 包含项目名、简介、安装、快速开始、配置、开发等部分;CHANGELOG 采用 Keep a Changelog 格式,包含 Unreleased、Added、Changed、Fixed 等小节。
六、最佳实践摘要 使用 ruff 作为统一的 lint 和格式化工具;启用严格 mypy 以在运行前捕获类型错误;行宽 120 字符;使用描述性名称;使用绝对导入;使用 Google 风格 docstring;为每个公开函数编写 docstring;将文档视为代码并保持更新;在 CI 中自动化,每次提交运行 linter;面向 Python 3.10+,新项目推荐 Python 3.12+ 以使用现代语言特性。