其他
需要统一 Python 代码风格、配置…
为新项目或团队建立 Python 代码风格、类型检查、命名、导入与 docstring 规范时使用。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 47/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 85/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 50/100 ×0.15
适用场景
需要统一 Python 代码风格、配置 通用
解决思路
- 安装现代工具链:pip install ruff mypy。
- 在 pyproject.toml 中配置 ruff:设置 line-length = 120、target-version = "py312"(按项目最低 Python 版本调整)。
- 在 [tool.ruff.lint] 中 select 规则:E(pycodestyle errors)、W(pycodestyle warnings)、F(pyflakes)、I(isort)、B(flake8-bugbear)、C4(flake8-comprehensions)、UP(pyupgrade)、SIM(flake8-simplify),并 ignore = ["E501"](行长交给格式化器处理)。
- 在 [tool.ruff.format] 中设置 quote-style = "double"、indent-style = "space"。
- 运行 ruff check --fix . 做 lint 并自动修复,运行 ruff format . 格式化代码。
- 在 pyproject.toml 的 [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"。
- 命名遵循 PEP 8 且清晰优先:文件名/模块用描述性 snake_case(如 user_repository.py、order_processing.py、http_client.py),避免缩写(如 usr_repo.py、ord_proc.py、http_cli.py)。
- 类名用 PascalCase(如 UserRepository、HTTPClientFactory,缩写保持大写),函数和变量用 snake_case(如 get_user_by_email、retry_count、max_connections)。
- 模块级常量用 SCREAMING_SNAKE_CASE(如 MAX_RETRY_ATTEMPTS、DEFAULT_TIMEOUT_SECONDS、API_BASE_URL)。
- 导入按标准库、第三方、本地三组排序(如先 os/collections.abc/typing,再 httpx/pydantic/sqlalchemy,最后 myproject.models/myproject.services)。
- 只使用绝对导入(如 from myproject.utils import retry_decorator),避免相对导入(如 from ..utils import retry_decorator)。
- 为所有公开类、方法和函数写 Google 风格 docstring;简单函数写一行摘要(如 """Retrieve a user by their unique identifier.""")。
- 复杂函数 docstring 包含摘要、Args、Returns、Raises、Example 段落(如 process_batch 的 items、max_workers、on_progress 参数说明)。
- 类 docstring 包含摘要、Attributes 和 Example(如 UserService 的 repository、logger 属性示例)。
- 行长设为 120 字符,长函数签名、链式调用和长字符串用括号换行保持可读(如 create_user 参数分行、db.query 链式分行、f-string 拼接分行)。
- README 包含项目名、简介、Installation、Quick Start、Configuration、Development 等章节。
- CHANGELOG 采用 Keep a Changelog 格式,包含 Unreleased 及 Added、Changed、Fixed 小节。
- 在 CI 中每次提交自动运行 linter。
- 新项目目标 Python 3.10+,推荐 Python 3.12+ 以使用现代语言特性。