python-comments
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Comments
Python代码注释
Purpose
用途
Two operational modes for Python code comments:
- Write mode - Add missing comments, improve existing ones, fix negative-type comments
- Audit mode - Classify all comments, identify gaps, produce structured quality report
Core principle: comments explain why, code explains what. Type hints explain types.
Python代码注释的两种操作模式:
- 编写模式 - 添加缺失的注释,改进现有注释,修复负面类型的注释
- 审核模式 - 对所有注释进行分类,识别缺失项,生成结构化质量报告
核心原则:注释解释为什么,代码解释是什么,类型提示解释类型。
When to Invoke
触发场景
Write mode triggers:
- User requests "add comments", "document this", "improve comments"
- Code review flags missing docstrings or unclear logic
- New module/class/function lacks documentation
- Complex algorithm or business rule needs explanation
Audit mode triggers:
- User requests "review comments", "comment quality", "documentation audit"
- Pre-release documentation review
- Onboarding prep for new team members
- Legacy code assessment
编写模式触发条件:
- 用户请求“添加注释”、“为这段代码编写文档”、“改进注释”
- 代码评审标记缺失文档字符串或逻辑不清晰
- 新模块/类/函数缺少文档
- 复杂算法或业务规则需要说明
审核模式触发条件:
- 用户请求“评审注释”、“注释质量检查”、“文档审核”
- 发布前的文档评审
- 为新团队成员准备的入职资料
- 遗留代码评估
When NOT to Invoke
不适用场景
- Code is scheduled for deletion
- User wants API reference generation (use documentation tools instead)
- User wants type stub generation (use type hint tools instead)
- Trivial scripts or one-off scripts where comments add no value
- 代码已计划删除
- 用户需要生成API参考文档(请使用专门的文档工具)
- 用户需要生成类型存根(请使用类型提示工具)
- 简单脚本或一次性脚本,添加注释无实际价值
Antirez Comment Taxonomy for Python
适用于Python的Antirez注释分类法
Nine comment types from antirez's "Writing system software: code comments". See for full detail.
references/taxonomy.md来自antirez《编写系统软件:代码注释》的9类注释类型。详细内容请参考。
references/taxonomy.mdPositive Types (write these)
正面类型(建议编写)
| Type | Name | Python Form | Purpose |
|---|---|---|---|
| 1 | Function | Docstring | What the function/class/module does |
| 2 | Design | Docstring or | Architecture rationale, API design choices |
| 3 | Why | Inline | Non-obvious reasoning behind code |
| 4 | Teacher | Inline | Domain knowledge, algorithm explanation |
| 5 | Checklist | Inline | Steps that must not be skipped or reordered |
| 6 | Guide | | Navigation aids in long modules |
| 类型 | 名称 | Python形式 | 用途 |
|---|---|---|---|
| 1 | 函数型 | Docstring | 说明函数/类/模块的功能 |
| 2 | 设计型 | Docstring或 | 说明架构原理、API设计选择 |
| 3 | 原因型 | 行内 | 解释代码背后非显而易见的逻辑 |
| 4 | 教学型 | 行内 | 说明领域知识、算法原理 |
| 5 | 检查清单型 | 行内 | 标记不可跳过或重新排序的步骤 |
| 6 | 导航型 | | 长模块中的导航辅助标记 |
Negative Types (detect and fix these)
负面类型(需检测并修复)
| Type | Name | Detection | Fix |
|---|---|---|---|
| 7 | Trivial | Restates the code | Delete |
| 8 | Debt | | Resolve or create issue |
| 9 | Backup | Commented-out code | Delete (git preserves history) |
| 类型 | 名称 | 检测方式 | 修复方案 |
|---|---|---|---|
| 7 | 冗余型 | 重复代码内容 | 删除 |
| 8 | 债务型 | 包含 | 解决问题或创建跟踪工单 |
| 9 | 备份型 | 被注释掉的代码 | 删除(Git会保留历史记录) |
Python-Specific Mapping
Python特定映射
Docstrings vs Inline Comments
文档字符串 vs 行内注释
- Docstrings () - Types 1-2. Describe interface (what, args, returns, raises). Follow PEP 257.
"""...""" - Inline comments () - Types 3-6. Describe implementation (why, how, context).
# - Type hints - Reduce comment burden. Document semantics in docstrings, not types.
- Docstrings () - 对应类型1-2。描述接口(功能、参数、返回值、异常)。遵循PEP 257规范。
"""...""" - 行内注释 () - 对应类型3-6。描述实现细节(原因、方式、上下文)。
# - 类型提示 - 减少注释负担。在文档字符串中描述语义,而非重复类型信息。
Type Hints Reduce Comment Burden
类型提示减少注释负担
python
undefinedpython
undefinedBAD: Comment duplicates type hint
错误示例:注释重复类型提示
def process(data: list[dict]) -> bool:
"""Process data.
Args:
data: A list of dictionaries # Redundant - type hint says this
"""def process(data: list[dict]) -> bool:
"""Process data.
Args:
data: A list of dictionaries # 冗余 - 类型提示已说明
"""GOOD: Docstring adds semantic meaning
正确示例:文档字符串添加语义信息
def process(data: list[dict]) -> bool:
"""Process sensor readings and flag anomalies.
Args:
data: Sensor readings keyed by timestamp, each containing
'value', 'unit', and optional 'calibration_offset'
"""undefineddef process(data: list[dict]) -> bool:
"""处理传感器读数并标记异常。
Args:
data: 按时间戳索引的传感器读数,每条包含
'value'、'unit'和可选的'calibration_offset'
"""undefinedPEP 257 Essentials
PEP 257核心要点
- One-line docstrings: (imperative mood, period)
"""Return the user's full name.""" - Multi-line: summary line, blank line, elaboration
- All public modules, classes, functions, methods need docstrings
- Private methods: docstring if logic is non-obvious
- 单行文档字符串:(使用祈使语气,结尾加句号)
"""返回用户的全名。""" - 多行文档字符串:摘要行、空行、详细说明
- 所有公共模块、类、函数、方法都需要文档字符串
- 私有方法:如果逻辑非显而易见,需要添加文档字符串
Write Mode Workflow
编写模式工作流程
Execute in four phases.
分为四个阶段执行。
Phase 1: Scan
阶段1:扫描
- Read entire file/module being commented
- Identify all existing comments and docstrings
- Map code structure: modules, classes, functions, complex blocks
- Note type hints already present (reduces docstring burden)
Output: Inventory of existing documentation and code structure.
- 读取需要添加注释的整个文件/模块
- 识别所有现有注释和文档字符串
- 梳理代码结构:模块、类、函数、复杂代码块
- 记录已有的类型提示(减少文档字符串的编写负担)
输出结果: 现有文档和代码结构的清单。
Phase 2: Classify Gaps
阶段2:分类缺失项
For each code element, determine what's missing:
- Module-level - Missing module docstring? Missing guide comments for sections?
- Class-level - Missing class docstring? Missing design rationale?
- Function-level - Missing docstring? Missing parameter semantics? Missing why-comments on complex logic?
- Block-level - Complex algorithms without teacher comments? Non-obvious conditions without why-comments? Multi-step processes without checklist comments?
Prioritize gaps by impact:
- Critical - Public API without docstring, complex algorithm without explanation
- High - Non-obvious business rule without why-comment, multi-step process without checklist
- Medium - Missing guide comments in long modules, missing design rationale
- Low - Private helpers without docstrings (skip if logic is obvious)
Output: Prioritized gap list with comment type needed for each.
针对每个代码元素,确定缺失的内容:
- 模块级 - 是否缺失模块文档字符串?是否缺失章节导航注释?
- 类级 - 是否缺失类文档字符串?是否缺失设计原理说明?
- 函数级 - 是否缺失文档字符串?是否缺失参数语义说明?是否缺失复杂逻辑的原因型注释?
- 代码块级 - 复杂算法是否缺少教学型注释?非显而易见的条件判断是否缺少原因型注释?多步骤流程是否缺少检查清单型注释?
按影响程度优先处理缺失项:
- 关键 - 公共API缺少文档字符串,复杂算法缺少说明
- 高 - 非显而易见的业务规则缺少原因型注释,多步骤流程缺少检查清单
- 中 - 长模块缺少导航型注释,缺少设计原理说明
- 低 - 私有辅助函数缺少文档字符串(如果逻辑简单可跳过)
输出结果: 按优先级排序的缺失项列表,标注每个项所需的注释类型。
Phase 3: Write
阶段3:编写注释
Apply comments following these rules:
- Choose correct type - Use taxonomy from Phase 2 classification
- Choose correct form - Docstring for types 1-2, inline for types 3-6
# - Choose correct style - Match project's existing docstring style; default to Google style. See
references/docstring-styles.md - Write concisely - Every word must earn its place
- Fix negatives - Delete trivial comments (type 7), resolve or issue-track debt (type 8), delete backup code (type 9)
Writing rules per type:
- Type 1 (Function): Imperative mood. Document purpose, args semantics (not types if hints exist), returns, raises, side effects. See
references/docstring-styles.md - Type 2 (Design): Explain why this approach over alternatives. Place at module/class level or above complex function
- Type 3 (Why): One line above the non-obvious code. Start with "why" reasoning, not "what" description
- Type 4 (Teacher): Explain domain concept or algorithm. Link to external reference if applicable
- Type 5 (Checklist): Number the steps. Mark order-dependent sequences. Note what breaks if skipped
- Type 6 (Guide): Section headers in long modules. Use or
# --- Section Name ---/# region# endregion
Output: Commented code.
遵循以下规则添加注释:
- 选择正确类型 - 使用阶段2分类确定的注释类型
- 选择正确形式 - 类型1-2使用Docstring,类型3-6使用行内
# - 选择正确风格 - 匹配项目现有文档字符串风格;默认使用Google风格。请参考
references/docstring-styles.md - 简洁明了 - 每个词都要有实际意义
- 修复负面类型 - 删除冗余注释(类型7),解决或跟踪债务型注释(类型8),删除备份型代码(类型9)
各类型注释编写规则:
- 类型1(函数型): 使用祈使语气。说明功能、参数语义(如果已有类型提示则无需重复类型)、返回值、异常、副作用。请参考
references/docstring-styles.md - 类型2(设计型): 说明为什么选择该方案而非其他方案。放置在模块/类级别或复杂函数上方
- 类型3(原因型): 在非显而易见的代码上方添加单行注释。先说明原因,而非描述代码功能
- 类型4(教学型): 解释领域概念或算法。如有需要可链接外部参考资料
- 类型5(检查清单型): 为步骤编号。标记顺序敏感的流程。说明跳过步骤的后果
- 类型6(导航型): 长模块中的章节标题。使用或
# --- 章节名称 ---/# region格式# endregion
输出结果: 添加注释后的代码。
Phase 4: Verify
阶段4:验证
- No trivial comments added - Every comment adds information not in the code
- No type duplication - Docstrings don't repeat type hints
- Style consistency - All docstrings follow the same style (Google/NumPy/Sphinx)
- Existing comments preserved - Don't delete valid existing comments unless explicitly negative types
- Code unchanged - Only comments/docstrings modified, zero logic changes
Output: Final commented code passing all checks.
- 无冗余注释 - 所有注释都提供了代码未包含的信息
- 无类型重复 - 文档字符串不重复类型提示内容
- 风格一致 - 所有文档字符串遵循相同风格(Google/NumPy/Sphinx)
- 保留有效注释 - 仅修改/删除负面类型(7-9)或明显错误的注释
- 不修改代码逻辑 - 仅修改注释和文档字符串,不做任何功能性变更
输出结果: 通过所有检查的最终注释代码。
Audit Mode Workflow
审核模式工作流程
Execute in four phases.
分为四个阶段执行。
Phase 1: Collect
阶段1:收集
- Extract all comments and docstrings from target code
- Record location (file, line, scope)
- Record form (docstring, inline , block
#)# - Record associated code element (module, class, function, block)
Output: Comment inventory with locations.
- 从目标代码中提取所有注释和文档字符串
- 记录位置(文件、行号、作用域)
- 记录形式(文档字符串、行内、块级
#)# - 记录关联的代码元素(模块、类、函数、代码块)
输出结果: 带位置信息的注释清单。
Phase 2: Classify
阶段2:分类
For each comment, assign:
- Type (1-9 from taxonomy)
- Quality (good / adequate / poor)
- Accuracy (correct / outdated / misleading)
Quality criteria per type - see for detail:
references/taxonomy.md- Type 1 (Function): Covers purpose, args, returns, raises? Imperative mood?
- Type 2 (Design): Explains rationale? References alternatives considered?
- Type 3 (Why): Explains reasoning, not just restates code?
- Type 4 (Teacher): Accurate domain explanation? Links to sources?
- Type 5 (Checklist): Steps numbered? Consequences of skipping noted?
- Type 6 (Guide): Consistent format? Matches actual code sections?
- Type 7 (Trivial): Delete candidate
- Type 8 (Debt): Has actionable resolution path?
- Type 9 (Backup): Delete candidate
Output: Classified comment inventory with quality assessments.
为每个注释分配:
- 类型(分类法中的1-9类)
- 质量(良好/合格/较差)
- 准确性(正确/过时/误导)
各类型质量标准 - 详细内容请参考:
references/taxonomy.md- 类型1(函数型):是否涵盖功能、参数、返回值、异常?是否使用祈使语气?
- 类型2(设计型):是否解释了设计原理?是否提及考虑过的替代方案?
- 类型3(原因型):是否解释了逻辑原因,而非重复代码内容?
- 类型4(教学型):领域知识解释是否准确?是否链接到参考资料?
- 类型5(检查清单型):步骤是否编号?是否说明跳过步骤的后果?
- 类型6(导航型):格式是否一致?是否匹配实际代码章节?
- 类型7(冗余型):建议删除
- 类型8(债务型):是否有可执行的解决路径?
- 类型9(备份型):建议删除
输出结果: 带质量评估的分类注释清单。
Phase 3: Gap Analysis
阶段3:缺失项分析
Identify what's missing:
- Public API coverage - Percentage of public functions/classes/modules with docstrings
- Why-comment coverage - Complex logic blocks with non-obvious reasoning explained
- Design documentation - Architecture decisions documented at module/class level
- Negative type count - Number of trivial, debt, and backup comments
Severity levels:
- Critical - Public API without docstrings, misleading comments
- High - Complex logic without why-comments, outdated comments
- Medium - Missing design rationale, missing guide comments
- Low - Missing private method docstrings, minor style inconsistencies
Output: Gap analysis with severity ratings.
识别缺失的内容:
- 公共API覆盖率 - 带文档字符串的公共函数/类/模块占比
- 原因型注释覆盖率 - 复杂逻辑块是否有非显而易见的原因说明
- 设计文档覆盖率 - 模块/类级别的架构决策是否有文档说明
- 负面类型数量 - 冗余、债务、备份型注释的数量
严重程度等级:
- 关键 - 公共API缺少文档字符串,存在误导性注释
- 高 - 复杂逻辑缺少原因型注释,注释过时
- 中 - 缺少设计原理说明,缺少导航型注释
- 低 - 私有方法缺少文档字符串,轻微风格不一致
输出结果: 带严重程度评级的缺失项分析报告。
Phase 4: Report
阶段4:生成报告
Generate structured audit report.
生成结构化审核报告。
Audit Report Format
审核报告格式
undefinedundefinedComment Audit Report
注释审核报告
Summary
摘要
- Files analyzed: N
- Total comments: N (docstrings: N, inline: N)
- Comment density: N comments per 100 LOC
- Type distribution: Type 1: N, Type 2: N, ... Type 9: N
- Quality score: N/10
- 分析文件数: N
- 总注释数: N(文档字符串:N,行内:N)
- 注释密度: 每100行代码N条注释
- 类型分布: 类型1:N,类型2:N,... 类型9:N
- 质量得分: N/10
Critical Gaps
关键缺失项
- {file}:{line} - {element} - Missing {type} comment - {impact}
- {文件}:{行号} - {元素} - 缺失{类型}注释 - {影响}
Issues Found
发现的问题
Negative Comments (fix or remove)
负面类型注释(需修复或删除)
- {file}:{line} - Type {N} ({name}) - "{comment text}" - Action: {delete/resolve/rewrite}
- {文件}:{行号} - 类型{N}({名称}) - "{注释文本}" - 操作建议:{删除/解决/重写}
Outdated Comments
过时注释
- {file}:{line} - "{comment text}" - Mismatch: {description}
- {文件}:{行号} - "{注释文本}" - 不匹配:{描述}
Quality Issues
质量问题
- {file}:{line} - Type {N} - Issue: {description}
- {文件}:{行号} - 类型{N} - 问题:{描述}
Coverage Metrics
覆盖率指标
| Scope | With Docstring | Without | Coverage |
|---|---|---|---|
| Modules | N | N | N% |
| Classes | N | N | N% |
| Public functions | N | N | N% |
| Public methods | N | N | N% |
| 作用域 | 带文档字符串 | 无文档字符串 | 覆盖率 |
|---|---|---|---|
| 模块 | N | N | N% |
| 类 | N | N | N% |
| 公共函数 | N | N | N% |
| 公共方法 | N | N | N% |
Recommendations
建议
- Priority 1: {action} - {N elements affected}
- Priority 2: {action} - {N elements affected}
- Priority 3: {action} - {N elements affected}
- 优先级1: {操作} - 影响{N}个元素
- 优先级2: {操作} - 影响{N}个元素
- 优先级3: {操作} - 影响{N}个元素
Comment Style
注释风格
- Detected style: {Google/NumPy/Sphinx/mixed}
- Consistency: {consistent/inconsistent}
- Recommendation: {standardize on X style}
See `references/examples/audit-mode-examples.md` for complete report examples.- 检测到的风格: {Google/NumPy/Sphinx/混合}
- 一致性: {一致/不一致}
- 建议: {统一使用X风格}
完整报告示例请参考`references/examples/audit-mode-examples.md`。Key Constraints
核心约束
- NEVER add trivial comments - If the code says , do not add
x += 1# increment x - NEVER add placeholder docstrings - on a complex function is worse than nothing
"""Process data.""" - NEVER duplicate type hints - If type hints exist, document semantics not types
- NEVER change code logic - Comments and docstrings only, zero functional changes
- PRESERVE existing style - Match the project's existing docstring style
- PRESERVE valid comments - Only modify/delete comments that are negative types (7-9) or demonstrably wrong
- 绝对禁止添加冗余注释 - 如果代码是,请勿添加
x += 1# increment x - 绝对禁止添加占位符文档字符串 - 复杂函数上仅写比没有注释更差
"""Process data."" - 绝对禁止重复类型提示 - 如果已有类型提示,文档字符串应说明语义而非类型
- 绝对禁止修改代码逻辑 - 仅修改注释和文档字符串,不做任何功能性变更
- 保留现有风格 - 匹配项目已有的文档字符串风格
- 保留有效注释 - 仅修改/删除负面类型(7-9)或明显错误的注释
Integration with Same-Package Skills
与同包技能的集成
- python-refactor - Refactoring may require updating comments. Run write mode after refactoring to update docstrings
- python-testing-patterns - Test docstrings benefit from type 1 (function) comments. Audit mode can assess test documentation
- python-performance-optimization - Performance-critical code benefits from type 4 (teacher) comments explaining algorithm choices
- python-packaging - Package-level documentation (docstrings) follows type 1+2 patterns
__init__.py
- python-refactor - 重构可能需要更新注释。重构完成后运行编写模式更新文档字符串
- python-testing-patterns - 测试用例的文档字符串可使用类型1(函数型)注释。审核模式可评估测试文档质量
- python-performance-optimization - 性能关键代码可通过类型4(教学型)注释说明算法选择
- python-packaging - 包级文档(文档字符串)遵循类型1+2的模式
__init__.py