python-style-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Style Guide

Python风格指南

Overview

概述

Use this skill to review and improve Python code for correctness, readability, and production reliability.
使用本指南来评审并优化Python代码的正确性、可读性及生产环境可靠性。

Scope Boundaries

适用边界

  • Use this skill when the task matches the trigger condition described in
    description
    .
  • Do not use this skill when the primary task falls outside this skill's domain.
  • 当任务匹配
    description
    中描述的触发条件时使用本指南。
  • 当核心任务不属于本指南的适用领域时请勿使用。

Trigger Reference

触发规则参考

  • Use
    references/trigger-matrix.md
    as the canonical trigger and co-activation matrix.
  • Resolve skill activation from changed files with
    python3 scripts/resolve_style_guides.py <changed-path>...
    when automation is available.
  • Validate trigger matrix consistency with
    python3 scripts/validate_trigger_matrix_sync.py
    .
  • 使用
    references/trigger-matrix.md
    作为标准触发与联动激活矩阵。
  • 具备自动化条件时,可通过
    python3 scripts/resolve_style_guides.py <changed-path>...
    根据变更文件确定需要启用的风格指南。
  • 通过
    python3 scripts/validate_trigger_matrix_sync.py
    验证触发矩阵的一致性。

Quality Gate Reference

质量门禁参考

  • Use
    references/quality-gate-command-matrix.md
    for CI check-only vs local autofix command mapping.
  • 使用
    references/quality-gate-command-matrix.md
    获取CI仅检查命令与本地自动修复命令的映射关系。

Shared References

共享参考

  • Typing and boundary rules:
    • references/typing-and-boundary-rules.md
  • 类型标注与边界规则:
    • references/typing-and-boundary-rules.md

Templates And Assets

模板与资产

  • Python review checklist:
    • assets/python-review-checklist.md
  • Refactor plan template:
    • assets/python-refactor-plan-template.md
  • Python评审检查清单:
    • assets/python-review-checklist.md
  • 重构计划模板:
    • assets/python-refactor-plan-template.md

Inputs To Gather

需收集的输入信息

  • Changed modules and impacted boundaries.
  • Typing and data-modeling risk hotspots.
  • Error/config/security constraints.
  • CI and runtime quality gate expectations.
  • 变更模块及受影响的边界。
  • 类型标注与数据建模风险热点。
  • 错误/配置/安全约束。
  • CI与运行时质量门禁预期要求。

Deliverables

交付物

  • Risk-prioritized review findings.
  • Refactor plan with validation strategy.
  • Merge readiness decision with residual risks.
  • 按风险优先级排序的评审发现。
  • 包含验证策略的重构计划。
  • 附带剩余风险说明的合并就绪判定。

Workflow

工作流程

  1. Confirm trigger fit and impacted Python artifacts.
  2. Plan changes via
    assets/python-refactor-plan-template.md
    .
  3. Review with
    assets/python-review-checklist.md
    and project gates.
  4. Apply improvements for typing, boundaries, and failure visibility.
  5. Execute required checks and publish residual-risk ownership.
  1. 确认触发匹配及受影响的Python工件。
  2. 参考
    assets/python-refactor-plan-template.md
    制定变更计划。
  3. 使用
    assets/python-review-checklist.md
    和项目门禁规则进行评审。
  4. 针对类型标注、边界、故障可见性方面进行优化。
  5. 执行所需检查并公示剩余风险的责任人。

Review And Refactor Checklist

评审与重构检查清单

Architecture and module boundaries

架构与模块边界

  1. Keep modules cohesive and focused on one responsibility.
  2. Isolate side effects (I/O, network, DB) behind clear interfaces.
  3. Keep orchestration layers thin and move business rules into domain modules.
  4. Avoid circular imports by keeping dependency direction explicit.
  1. 保持模块内聚,专注于单一职责。
  2. 将副作用(I/O、网络、数据库)隔离在清晰的接口之后。
  3. 保持编排层轻量化,将业务规则迁移到领域模块中。
  4. 保持依赖方向明确,避免循环导入。

Naming and code structure

命名与代码结构

  1. Follow PEP 8 naming conventions (
    snake_case
    ,
    PascalCase
    ,
    UPPER_CASE
    constants).
  2. Write small functions with explicit inputs/outputs.
  3. Replace magic numbers with named constants including units (
    REQUEST_TIMEOUT_SECONDS
    ).
  4. Add short comments only where intent is non-obvious.
  1. 遵循PEP 8命名规范(
    snake_case
    PascalCase
    、常量使用
    UPPER_CASE
    )。
  2. 编写具备显式输入输出的小型函数。
  3. 使用带单位的命名常量替换魔法数字(如
    REQUEST_TIMEOUT_SECONDS
    )。
  4. 仅在意图不明确时添加简短注释。

Typing and data modeling

类型标注与数据建模

  1. Add type hints for public functions, methods, and complex locals.
  2. Prefer explicit models (
    dataclass
    ,
    TypedDict
    , Pydantic model) over loose dicts.
  3. Avoid
    Any
    unless unavoidable and justified inline.
  4. Define precise protocols/interfaces for pluggable dependencies.
  5. Avoid
    dict[str, Any]
    and
    object
    for domain payloads when structure is known.
  6. Convert untyped external input into explicit models once at the boundary, then keep inner layers strongly shaped.
  7. Treat repeated
    typing.cast(...)
    usage as a signal to redesign the underlying type contract.
  1. 为公共函数、方法和复杂局部变量添加类型提示。
  2. 优先使用显式模型(
    dataclass
    TypedDict
    、Pydantic model)而非松散的字典。
  3. 除非不可避免且有行内说明,否则避免使用
    Any
  4. 为可插拔依赖定义精确的协议/接口。
  5. 结构已知的领域 payload 避免使用
    dict[str, Any]
    object
    类型。
  6. 在边界处将无类型的外部输入一次性转换为显式模型,保持内部层强类型结构。
  7. 将重复使用
    typing.cast(...)
    视为需要重新设计底层类型契约的信号。

Error handling and control flow

错误处理与控制流

  1. Raise specific exception types with actionable messages.
  2. Catch exceptions intentionally at boundaries and preserve causal chains.
  3. Avoid broad
    except Exception
    unless rethrowing after required cleanup/logging.
  4. Do not suppress failures with silent fallback logic by default.
  1. 抛出携带可操作信息的特定异常类型。
  2. 在边界处有意识地捕获异常并保留因果链。
  3. 除非在完成必要的清理/日志记录后重新抛出,否则避免使用宽泛的
    except Exception
  4. 默认情况下不要使用静默回退逻辑隐藏故障。

Configuration and environment

配置与环境

  1. Parse and validate configuration at startup.
  2. Fail startup when required environment variables are missing.
  3. Do not hardcode fallback defaults for required environment variables.
  4. Keep secrets in secret managers or injected environment, never in code.
  1. 在服务启动时解析并验证配置。
  2. 缺失必填环境变量时启动失败。
  3. 不要为必填环境变量硬编码回退默认值。
  4. 将密钥存储在密钥管理器或注入的环境变量中,绝对不要写入代码。

Security and compliance

安全与合规

  1. Validate untrusted input at boundaries.
  2. Use parameterized DB queries; never build SQL with string concatenation.
  3. Avoid unsafe deserialization and command execution with unchecked input.
  4. Redact secrets and sensitive fields from logs.
  1. 在边界处验证不受信任的输入。
  2. 使用参数化数据库查询;绝对不要通过字符串拼接构建SQL。
  3. 避免使用未校验输入进行不安全的反序列化和命令执行。
  4. 在日志中脱敏密钥和敏感字段。

Performance and efficiency

性能与效率

  1. Measure bottlenecks before optimizing (
    cProfile
    , tracing, metrics).
  2. Avoid N+1 data access patterns and repeated expensive computation.
  3. Stream large datasets instead of loading everything into memory.
  4. Use bounded retries/backoff with named constants.
  1. 优化前先通过(
    cProfile
    、链路追踪、指标)测量瓶颈。
  2. 避免N+1数据访问模式和重复的高开销计算。
  3. 流式处理大型数据集而非全量加载到内存。
  4. 使用带命名常量的有限重试/退避策略。

Testing and verification

测试与验证

  1. Add unit tests for core logic and integration tests for boundaries.
  2. Cover edge cases: invalid data, timeout, retry exhaustion, concurrency hazards.
  3. Add regression tests for every bug fix.
  4. Document manual verification when automation cannot cover behavior.
  1. 为核心逻辑添加单元测试,为边界场景添加集成测试。
  2. 覆盖边缘case:无效数据、超时、重试耗尽、并发风险。
  3. 每个Bug修复都要添加回归测试。
  4. 自动化无法覆盖的行为要编写手动验证说明。

Observability and operations

可观测性与运维

  1. Use structured logs with trace/request IDs.
  2. Emit metrics for latency, throughput, and errors.
  3. Normalize exception-to-error response mapping at API boundaries.
  4. Ensure alertable signals exist for critical failure paths.
  1. 使用携带链路/请求ID的结构化日志。
  2. 上报延迟、吞吐量和错误相关指标。
  3. 在API边界处统一异常到错误响应的映射规则。
  4. 确保关键故障路径存在可告警的信号。

CI required quality gates (check-only)

CI必填质量门禁(仅检查)

  1. Run
    uv run ruff format --check .
    .
  2. Run
    uv run ruff check .
    .
  3. Run
    uv run mypy .
    (or project type checker equivalent).
  4. Run
    uv run pytest -q
    .
  1. 执行
    uv run ruff format --check .
  2. 执行
    uv run ruff check .
  3. 执行
    uv run mypy .
    (或项目等价的类型检查器)。
  4. 执行
    uv run pytest -q

Optional autofix commands (local)

可选自动修复命令(本地)

  1. Run
    uv run ruff format .
    .
  2. Run
    uv run ruff check --fix .
    , then re-run checks.
  1. 执行
    uv run ruff format .
  2. 执行
    uv run ruff check --fix .
    ,然后重新运行检查。

Failure Conditions

终止条件

  • Stop when boundary contracts remain ambiguous after review.
  • Stop when required configuration or typing guarantees are missing.
  • Escalate when unresolved defects threaten correctness or operability.
  • 评审后边界契约仍然不明确时终止。
  • 缺失必填配置或类型保证时终止。
  • 未解决的缺陷威胁到正确性或可运行性时上报。