python-comments

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Comments

Python代码注释

Purpose

用途

Two operational modes for Python code comments:
  1. Write mode - Add missing comments, improve existing ones, fix negative-type comments
  2. Audit mode - Classify all comments, identify gaps, produce structured quality report
Core principle: comments explain why, code explains what. Type hints explain types.
Python代码注释的两种操作模式:
  1. 编写模式 - 添加缺失的注释,改进现有注释,修复负面类型的注释
  2. 审核模式 - 对所有注释进行分类,识别缺失项,生成结构化质量报告
核心原则:注释解释为什么,代码解释是什么,类型提示解释类型

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
references/taxonomy.md
for full detail.
来自antirez《编写系统软件:代码注释》的9类注释类型。详细内容请参考
references/taxonomy.md

Positive Types (write these)

正面类型(建议编写)

TypeNamePython FormPurpose
1FunctionDocstringWhat the function/class/module does
2DesignDocstring or
#
Architecture rationale, API design choices
3WhyInline
#
Non-obvious reasoning behind code
4TeacherInline
#
Domain knowledge, algorithm explanation
5ChecklistInline
#
Steps that must not be skipped or reordered
6Guide
#
section headers
Navigation aids in long modules
类型名称Python形式用途
1函数型Docstring说明函数/类/模块的功能
2设计型Docstring或
#
说明架构原理、API设计选择
3原因型行内
#
解释代码背后非显而易见的逻辑
4教学型行内
#
说明领域知识、算法原理
5检查清单型行内
#
标记不可跳过或重新排序的步骤
6导航型
#
章节标题
长模块中的导航辅助标记

Negative Types (detect and fix these)

负面类型(需检测并修复)

TypeNameDetectionFix
7TrivialRestates the codeDelete
8Debt
TODO
,
FIXME
,
HACK
Resolve or create issue
9BackupCommented-out codeDelete (git preserves history)
类型名称检测方式修复方案
7冗余型重复代码内容删除
8债务型包含
TODO
FIXME
HACK
解决问题或创建跟踪工单
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
undefined
python
undefined

BAD: 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'
"""
undefined
def process(data: list[dict]) -> bool: """处理传感器读数并标记异常。
Args:
    data: 按时间戳索引的传感器读数,每条包含
          'value'、'unit'和可选的'calibration_offset'
"""
undefined

PEP 257 Essentials

PEP 257核心要点

  • One-line docstrings:
    """Return the user's full name."""
    (imperative mood, period)
  • 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:扫描

  1. Read entire file/module being commented
  2. Identify all existing comments and docstrings
  3. Map code structure: modules, classes, functions, complex blocks
  4. Note type hints already present (reduces docstring burden)
Output: Inventory of existing documentation and code structure.
  1. 读取需要添加注释的整个文件/模块
  2. 识别所有现有注释和文档字符串
  3. 梳理代码结构:模块、类、函数、复杂代码块
  4. 记录已有的类型提示(减少文档字符串的编写负担)
输出结果: 现有文档和代码结构的清单。

Phase 2: Classify Gaps

阶段2:分类缺失项

For each code element, determine what's missing:
  1. Module-level - Missing module docstring? Missing guide comments for sections?
  2. Class-level - Missing class docstring? Missing design rationale?
  3. Function-level - Missing docstring? Missing parameter semantics? Missing why-comments on complex logic?
  4. 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.
针对每个代码元素,确定缺失的内容:
  1. 模块级 - 是否缺失模块文档字符串?是否缺失章节导航注释?
  2. 类级 - 是否缺失类文档字符串?是否缺失设计原理说明?
  3. 函数级 - 是否缺失文档字符串?是否缺失参数语义说明?是否缺失复杂逻辑的原因型注释?
  4. 代码块级 - 复杂算法是否缺少教学型注释?非显而易见的条件判断是否缺少原因型注释?多步骤流程是否缺少检查清单型注释?
按影响程度优先处理缺失项:
  • 关键 - 公共API缺少文档字符串,复杂算法缺少说明
  • - 非显而易见的业务规则缺少原因型注释,多步骤流程缺少检查清单
  • - 长模块缺少导航型注释,缺少设计原理说明
  • - 私有辅助函数缺少文档字符串(如果逻辑简单可跳过)
输出结果: 按优先级排序的缺失项列表,标注每个项所需的注释类型。

Phase 3: Write

阶段3:编写注释

Apply comments following these rules:
  1. Choose correct type - Use taxonomy from Phase 2 classification
  2. Choose correct form - Docstring for types 1-2, inline
    #
    for types 3-6
  3. Choose correct style - Match project's existing docstring style; default to Google style. See
    references/docstring-styles.md
  4. Write concisely - Every word must earn its place
  5. 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
    # --- Section Name ---
    or
    # region
    /
    # endregion
Output: Commented code.
遵循以下规则添加注释:
  1. 选择正确类型 - 使用阶段2分类确定的注释类型
  2. 选择正确形式 - 类型1-2使用Docstring,类型3-6使用行内
    #
  3. 选择正确风格 - 匹配项目现有文档字符串风格;默认使用Google风格。请参考
    references/docstring-styles.md
  4. 简洁明了 - 每个词都要有实际意义
  5. 修复负面类型 - 删除冗余注释(类型7),解决或跟踪债务型注释(类型8),删除备份型代码(类型9)
各类型注释编写规则:
  • 类型1(函数型): 使用祈使语气。说明功能、参数语义(如果已有类型提示则无需重复类型)、返回值、异常、副作用。请参考
    references/docstring-styles.md
  • 类型2(设计型): 说明为什么选择该方案而非其他方案。放置在模块/类级别或复杂函数上方
  • 类型3(原因型): 在非显而易见的代码上方添加单行注释。先说明原因,而非描述代码功能
  • 类型4(教学型): 解释领域概念或算法。如有需要可链接外部参考资料
  • 类型5(检查清单型): 为步骤编号。标记顺序敏感的流程。说明跳过步骤的后果
  • 类型6(导航型): 长模块中的章节标题。使用
    # --- 章节名称 ---
    # region
    /
    # endregion
    格式
输出结果: 添加注释后的代码。

Phase 4: Verify

阶段4:验证

  1. No trivial comments added - Every comment adds information not in the code
  2. No type duplication - Docstrings don't repeat type hints
  3. Style consistency - All docstrings follow the same style (Google/NumPy/Sphinx)
  4. Existing comments preserved - Don't delete valid existing comments unless explicitly negative types
  5. Code unchanged - Only comments/docstrings modified, zero logic changes
Output: Final commented code passing all checks.
  1. 无冗余注释 - 所有注释都提供了代码未包含的信息
  2. 无类型重复 - 文档字符串不重复类型提示内容
  3. 风格一致 - 所有文档字符串遵循相同风格(Google/NumPy/Sphinx)
  4. 保留有效注释 - 仅修改/删除负面类型(7-9)或明显错误的注释
  5. 不修改代码逻辑 - 仅修改注释和文档字符串,不做任何功能性变更
输出结果: 通过所有检查的最终注释代码。

Audit Mode Workflow

审核模式工作流程

Execute in four phases.
分为四个阶段执行。

Phase 1: Collect

阶段1:收集

  1. Extract all comments and docstrings from target code
  2. Record location (file, line, scope)
  3. Record form (docstring, inline
    #
    , block
    #
    )
  4. Record associated code element (module, class, function, block)
Output: Comment inventory with locations.
  1. 从目标代码中提取所有注释和文档字符串
  2. 记录位置(文件、行号、作用域)
  3. 记录形式(文档字符串、行内
    #
    、块级
    #
  4. 记录关联的代码元素(模块、类、函数、代码块)
输出结果: 带位置信息的注释清单。

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
references/taxonomy.md
for detail:
  • 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:
  1. Public API coverage - Percentage of public functions/classes/modules with docstrings
  2. Why-comment coverage - Complex logic blocks with non-obvious reasoning explained
  3. Design documentation - Architecture decisions documented at module/class level
  4. 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.
识别缺失的内容:
  1. 公共API覆盖率 - 带文档字符串的公共函数/类/模块占比
  2. 原因型注释覆盖率 - 复杂逻辑块是否有非显而易见的原因说明
  3. 设计文档覆盖率 - 模块/类级别的架构决策是否有文档说明
  4. 负面类型数量 - 冗余、债务、备份型注释的数量
严重程度等级:
  • 关键 - 公共API缺少文档字符串,存在误导性注释
  • - 复杂逻辑缺少原因型注释,注释过时
  • - 缺少设计原理说明,缺少导航型注释
  • - 私有方法缺少文档字符串,轻微风格不一致
输出结果: 带严重程度评级的缺失项分析报告。

Phase 4: Report

阶段4:生成报告

Generate structured audit report.
生成结构化审核报告。

Audit Report Format

审核报告格式

undefined
undefined

Comment 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

覆盖率指标

ScopeWith DocstringWithoutCoverage
ModulesNNN%
ClassesNNN%
Public functionsNNN%
Public methodsNNN%
作用域带文档字符串无文档字符串覆盖率
模块NNN%
NNN%
公共函数NNN%
公共方法NNN%

Recommendations

建议

  1. Priority 1: {action} - {N elements affected}
  2. Priority 2: {action} - {N elements affected}
  3. Priority 3: {action} - {N elements affected}
  1. 优先级1: {操作} - 影响{N}个元素
  2. 优先级2: {操作} - 影响{N}个元素
  3. 优先级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
    x += 1
    , do not add
    # increment x
  • NEVER add placeholder docstrings -
    """Process data."""
    on a complex function is worse than nothing
  • 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 (
    __init__.py
    docstrings) follows type 1+2 patterns
  • python-refactor - 重构可能需要更新注释。重构完成后运行编写模式更新文档字符串
  • python-testing-patterns - 测试用例的文档字符串可使用类型1(函数型)注释。审核模式可评估测试文档质量
  • python-performance-optimization - 性能关键代码可通过类型4(教学型)注释说明算法选择
  • python-packaging - 包级文档(
    __init__.py
    文档字符串)遵循类型1+2的模式