python-style-guide
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython 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 as the canonical trigger and co-activation matrix.
references/trigger-matrix.md - Resolve skill activation from changed files with when automation is available.
python3 scripts/resolve_style_guides.py <changed-path>... - 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 for CI check-only vs local autofix command mapping.
references/quality-gate-command-matrix.md
- 使用获取CI仅检查命令与本地自动修复命令的映射关系。
references/quality-gate-command-matrix.md
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
工作流程
- Confirm trigger fit and impacted Python artifacts.
- Plan changes via .
assets/python-refactor-plan-template.md - Review with and project gates.
assets/python-review-checklist.md - Apply improvements for typing, boundaries, and failure visibility.
- Execute required checks and publish residual-risk ownership.
- 确认触发匹配及受影响的Python工件。
- 参考制定变更计划。
assets/python-refactor-plan-template.md - 使用和项目门禁规则进行评审。
assets/python-review-checklist.md - 针对类型标注、边界、故障可见性方面进行优化。
- 执行所需检查并公示剩余风险的责任人。
Review And Refactor Checklist
评审与重构检查清单
Architecture and module boundaries
架构与模块边界
- Keep modules cohesive and focused on one responsibility.
- Isolate side effects (I/O, network, DB) behind clear interfaces.
- Keep orchestration layers thin and move business rules into domain modules.
- Avoid circular imports by keeping dependency direction explicit.
- 保持模块内聚,专注于单一职责。
- 将副作用(I/O、网络、数据库)隔离在清晰的接口之后。
- 保持编排层轻量化,将业务规则迁移到领域模块中。
- 保持依赖方向明确,避免循环导入。
Naming and code structure
命名与代码结构
- Follow PEP 8 naming conventions (,
snake_case,PascalCaseconstants).UPPER_CASE - Write small functions with explicit inputs/outputs.
- Replace magic numbers with named constants including units ().
REQUEST_TIMEOUT_SECONDS - Add short comments only where intent is non-obvious.
- 遵循PEP 8命名规范(、
snake_case、常量使用PascalCase)。UPPER_CASE - 编写具备显式输入输出的小型函数。
- 使用带单位的命名常量替换魔法数字(如)。
REQUEST_TIMEOUT_SECONDS - 仅在意图不明确时添加简短注释。
Typing and data modeling
类型标注与数据建模
- Add type hints for public functions, methods, and complex locals.
- Prefer explicit models (,
dataclass, Pydantic model) over loose dicts.TypedDict - Avoid unless unavoidable and justified inline.
Any - Define precise protocols/interfaces for pluggable dependencies.
- Avoid and
dict[str, Any]for domain payloads when structure is known.object - Convert untyped external input into explicit models once at the boundary, then keep inner layers strongly shaped.
- Treat repeated usage as a signal to redesign the underlying type contract.
typing.cast(...)
- 为公共函数、方法和复杂局部变量添加类型提示。
- 优先使用显式模型(、
dataclass、Pydantic model)而非松散的字典。TypedDict - 除非不可避免且有行内说明,否则避免使用。
Any - 为可插拔依赖定义精确的协议/接口。
- 结构已知的领域 payload 避免使用和
dict[str, Any]类型。object - 在边界处将无类型的外部输入一次性转换为显式模型,保持内部层强类型结构。
- 将重复使用视为需要重新设计底层类型契约的信号。
typing.cast(...)
Error handling and control flow
错误处理与控制流
- Raise specific exception types with actionable messages.
- Catch exceptions intentionally at boundaries and preserve causal chains.
- Avoid broad unless rethrowing after required cleanup/logging.
except Exception - Do not suppress failures with silent fallback logic by default.
- 抛出携带可操作信息的特定异常类型。
- 在边界处有意识地捕获异常并保留因果链。
- 除非在完成必要的清理/日志记录后重新抛出,否则避免使用宽泛的。
except Exception - 默认情况下不要使用静默回退逻辑隐藏故障。
Configuration and environment
配置与环境
- Parse and validate configuration at startup.
- Fail startup when required environment variables are missing.
- Do not hardcode fallback defaults for required environment variables.
- Keep secrets in secret managers or injected environment, never in code.
- 在服务启动时解析并验证配置。
- 缺失必填环境变量时启动失败。
- 不要为必填环境变量硬编码回退默认值。
- 将密钥存储在密钥管理器或注入的环境变量中,绝对不要写入代码。
Security and compliance
安全与合规
- Validate untrusted input at boundaries.
- Use parameterized DB queries; never build SQL with string concatenation.
- Avoid unsafe deserialization and command execution with unchecked input.
- Redact secrets and sensitive fields from logs.
- 在边界处验证不受信任的输入。
- 使用参数化数据库查询;绝对不要通过字符串拼接构建SQL。
- 避免使用未校验输入进行不安全的反序列化和命令执行。
- 在日志中脱敏密钥和敏感字段。
Performance and efficiency
性能与效率
- Measure bottlenecks before optimizing (, tracing, metrics).
cProfile - Avoid N+1 data access patterns and repeated expensive computation.
- Stream large datasets instead of loading everything into memory.
- Use bounded retries/backoff with named constants.
- 优化前先通过(、链路追踪、指标)测量瓶颈。
cProfile - 避免N+1数据访问模式和重复的高开销计算。
- 流式处理大型数据集而非全量加载到内存。
- 使用带命名常量的有限重试/退避策略。
Testing and verification
测试与验证
- Add unit tests for core logic and integration tests for boundaries.
- Cover edge cases: invalid data, timeout, retry exhaustion, concurrency hazards.
- Add regression tests for every bug fix.
- Document manual verification when automation cannot cover behavior.
- 为核心逻辑添加单元测试,为边界场景添加集成测试。
- 覆盖边缘case:无效数据、超时、重试耗尽、并发风险。
- 每个Bug修复都要添加回归测试。
- 自动化无法覆盖的行为要编写手动验证说明。
Observability and operations
可观测性与运维
- Use structured logs with trace/request IDs.
- Emit metrics for latency, throughput, and errors.
- Normalize exception-to-error response mapping at API boundaries.
- Ensure alertable signals exist for critical failure paths.
- 使用携带链路/请求ID的结构化日志。
- 上报延迟、吞吐量和错误相关指标。
- 在API边界处统一异常到错误响应的映射规则。
- 确保关键故障路径存在可告警的信号。
CI required quality gates (check-only)
CI必填质量门禁(仅检查)
- Run .
uv run ruff format --check . - Run .
uv run ruff check . - Run (or project type checker equivalent).
uv run mypy . - Run .
uv run pytest -q
- 执行。
uv run ruff format --check . - 执行。
uv run ruff check . - 执行(或项目等价的类型检查器)。
uv run mypy . - 执行。
uv run pytest -q
Optional autofix commands (local)
可选自动修复命令(本地)
- Run .
uv run ruff format . - Run , then re-run checks.
uv run ruff check --fix .
- 执行。
uv run ruff format . - 执行,然后重新运行检查。
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.
- 评审后边界契约仍然不明确时终止。
- 缺失必填配置或类型保证时终止。
- 未解决的缺陷威胁到正确性或可运行性时上报。