Python Comments
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.
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
Antirez Comment Taxonomy for Python
Nine comment types from antirez's "Writing system software: code comments". See references/taxonomy.md for full detail.
Positive 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 |
# section headers |
Navigation aids in long modules |
Negative Types (detect and fix these)
| Type |
Name |
Detection |
Fix |
| 7 |
Trivial |
Restates the code |
Delete |
| 8 |
Debt |
TODO, FIXME, HACK |
Resolve or create issue |
| 9 |
Backup |
Commented-out code |
Delete (git preserves history) |
Python-Specific Mapping
Docstrings vs Inline Comments
- 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.
Type Hints Reduce Comment Burden
# BAD: Comment duplicates type hint
def process(data: list[dict]) -> bool:
"""Process data.
Args:
data: A list of dictionaries # Redundant - type hint says this
"""
# 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'
"""
PEP 257 Essentials
- 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
- 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
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.
Phase 3: Write
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
# --- Section Name --- or # region/# endregion
Output: Commented code.
Phase 4: Verify
- 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.
Audit Mode Workflow
Execute in four phases.
Phase 1: Collect
- 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
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.
Phase 3: Gap Analysis
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.
Phase 4: Report
Generate structured audit report.
Audit Report Format
## 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
### 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}
#### Outdated Comments
- {file}:{line} - "{comment text}" - Mismatch: {description}
#### Quality Issues
- {file}:{line} - Type {N} - Issue: {description}
### 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% |
### Recommendations
1. **Priority 1:** {action} - {N elements affected}
2. **Priority 2:** {action} - {N elements affected}
3. **Priority 3:** {action} - {N elements affected}
### 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.
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
Integration with Same-Package Skills
- python-refactor - Refactoring may require updating comments. Run write mode after refactoring to update docstrings
- python-tdd - 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
1---2name: python-comments3description: Grade and rewrite code prose against antirez's 9-type taxonomy, mapped to PEP 257. TRIGGER WHEN: the user asks to improve comments, add docstrings, review comment quality, or audit documentation in a Python codebase.4---56# Python Comments78## Purpose910Two operational modes for Python code comments:11121. **Write mode** - Add missing comments, improve existing ones, fix negative-type comments132. **Audit mode** - Classify all comments, identify gaps, produce structured quality report1415Core principle: comments explain *why*, code explains *what*. Type hints explain *types*.1617## When to Invoke1819**Write mode triggers:**20- User requests "add comments", "document this", "improve comments"21- Code review flags missing docstrings or unclear logic22- New module/class/function lacks documentation23- Complex algorithm or business rule needs explanation2425**Audit mode triggers:**26- User requests "review comments", "comment quality", "documentation audit"27- Pre-release documentation review28- Onboarding prep for new team members29- Legacy code assessment3031## When NOT to Invoke3233- Code is scheduled for deletion34- User wants API reference generation (use documentation tools instead)35- User wants type stub generation (use type hint tools instead)36- Trivial scripts or one-off scripts where comments add no value3738## Antirez Comment Taxonomy for Python3940Nine comment types from antirez's "Writing system software: code comments". See `references/taxonomy.md` for full detail.4142### Positive Types (write these)4344| Type | Name | Python Form | Purpose |45|------|------|-------------|---------|46| 1 | Function | Docstring | What the function/class/module does |47| 2 | Design | Docstring or `#` | Architecture rationale, API design choices |48| 3 | Why | Inline `#` | Non-obvious reasoning behind code |49| 4 | Teacher | Inline `#` | Domain knowledge, algorithm explanation |50| 5 | Checklist | Inline `#` | Steps that must not be skipped or reordered |51| 6 | Guide | `#` section headers | Navigation aids in long modules |5253### Negative Types (detect and fix these)5455| Type | Name | Detection | Fix |56|------|------|-----------|-----|57| 7 | Trivial | Restates the code | Delete |58| 8 | Debt | `TODO`, `FIXME`, `HACK` | Resolve or create issue |59| 9 | Backup | Commented-out code | Delete (git preserves history) |6061## Python-Specific Mapping6263### Docstrings vs Inline Comments6465- **Docstrings** (`"""..."""`) - Types 1-2. Describe *interface* (what, args, returns, raises). Follow PEP 257.66- **Inline comments** (`#`) - Types 3-6. Describe *implementation* (why, how, context).67- **Type hints** - Reduce comment burden. Document *semantics* in docstrings, not types.6869### Type Hints Reduce Comment Burden7071```python72# BAD: Comment duplicates type hint73def process(data: list[dict]) -> bool:74 """Process data.7576 Args:77 data: A list of dictionaries # Redundant - type hint says this78 """7980# GOOD: Docstring adds semantic meaning81def process(data: list[dict]) -> bool:82 """Process sensor readings and flag anomalies.8384 Args:85 data: Sensor readings keyed by timestamp, each containing86 'value', 'unit', and optional 'calibration_offset'87 """88```8990### PEP 257 Essentials9192- One-line docstrings: `"""Return the user's full name."""` (imperative mood, period)93- Multi-line: summary line, blank line, elaboration94- All public modules, classes, functions, methods need docstrings95- Private methods: docstring if logic is non-obvious9697## Write Mode Workflow9899Execute in four phases.100101### Phase 1: Scan1021031. Read entire file/module being commented1042. Identify all existing comments and docstrings1053. Map code structure: modules, classes, functions, complex blocks1064. Note type hints already present (reduces docstring burden)107108**Output:** Inventory of existing documentation and code structure.109110### Phase 2: Classify Gaps111112For each code element, determine what's missing:1131141. **Module-level** - Missing module docstring? Missing guide comments for sections?1152. **Class-level** - Missing class docstring? Missing design rationale?1163. **Function-level** - Missing docstring? Missing parameter semantics? Missing why-comments on complex logic?1174. **Block-level** - Complex algorithms without teacher comments? Non-obvious conditions without why-comments? Multi-step processes without checklist comments?118119Prioritize gaps by impact:120- **Critical** - Public API without docstring, complex algorithm without explanation121- **High** - Non-obvious business rule without why-comment, multi-step process without checklist122- **Medium** - Missing guide comments in long modules, missing design rationale123- **Low** - Private helpers without docstrings (skip if logic is obvious)124125**Output:** Prioritized gap list with comment type needed for each.126127### Phase 3: Write128129Apply comments following these rules:1301311. **Choose correct type** - Use taxonomy from Phase 2 classification1322. **Choose correct form** - Docstring for types 1-2, inline `#` for types 3-61333. **Choose correct style** - Match project's existing docstring style; default to Google style. See `references/docstring-styles.md`1344. **Write concisely** - Every word must earn its place1355. **Fix negatives** - Delete trivial comments (type 7), resolve or issue-track debt (type 8), delete backup code (type 9)136137Writing rules per type:138- **Type 1 (Function):** Imperative mood. Document purpose, args semantics (not types if hints exist), returns, raises, side effects. See `references/docstring-styles.md`139- **Type 2 (Design):** Explain *why this approach* over alternatives. Place at module/class level or above complex function140- **Type 3 (Why):** One line above the non-obvious code. Start with "why" reasoning, not "what" description141- **Type 4 (Teacher):** Explain domain concept or algorithm. Link to external reference if applicable142- **Type 5 (Checklist):** Number the steps. Mark order-dependent sequences. Note what breaks if skipped143- **Type 6 (Guide):** Section headers in long modules. Use `# --- Section Name ---` or `# region`/`# endregion`144145**Output:** Commented code.146147### Phase 4: Verify1481491. **No trivial comments added** - Every comment adds information not in the code1502. **No type duplication** - Docstrings don't repeat type hints1513. **Style consistency** - All docstrings follow the same style (Google/NumPy/Sphinx)1524. **Existing comments preserved** - Don't delete valid existing comments unless explicitly negative types1535. **Code unchanged** - Only comments/docstrings modified, zero logic changes154155**Output:** Final commented code passing all checks.156157## Audit Mode Workflow158159Execute in four phases.160161### Phase 1: Collect1621631. Extract all comments and docstrings from target code1642. Record location (file, line, scope)1653. Record form (docstring, inline `#`, block `#`)1664. Record associated code element (module, class, function, block)167168**Output:** Comment inventory with locations.169170### Phase 2: Classify171172For each comment, assign:173- **Type** (1-9 from taxonomy)174- **Quality** (good / adequate / poor)175- **Accuracy** (correct / outdated / misleading)176177Quality criteria per type - see `references/taxonomy.md` for detail:178- Type 1 (Function): Covers purpose, args, returns, raises? Imperative mood?179- Type 2 (Design): Explains rationale? References alternatives considered?180- Type 3 (Why): Explains reasoning, not just restates code?181- Type 4 (Teacher): Accurate domain explanation? Links to sources?182- Type 5 (Checklist): Steps numbered? Consequences of skipping noted?183- Type 6 (Guide): Consistent format? Matches actual code sections?184- Type 7 (Trivial): Delete candidate185- Type 8 (Debt): Has actionable resolution path?186- Type 9 (Backup): Delete candidate187188**Output:** Classified comment inventory with quality assessments.189190### Phase 3: Gap Analysis191192Identify what's missing:1931. **Public API coverage** - Percentage of public functions/classes/modules with docstrings1942. **Why-comment coverage** - Complex logic blocks with non-obvious reasoning explained1953. **Design documentation** - Architecture decisions documented at module/class level1964. **Negative type count** - Number of trivial, debt, and backup comments197198Severity levels:199- **Critical** - Public API without docstrings, misleading comments200- **High** - Complex logic without why-comments, outdated comments201- **Medium** - Missing design rationale, missing guide comments202- **Low** - Missing private method docstrings, minor style inconsistencies203204**Output:** Gap analysis with severity ratings.205206### Phase 4: Report207208Generate structured audit report.209210## Audit Report Format211212```213## Comment Audit Report214215### Summary216- **Files analyzed:** N217- **Total comments:** N (docstrings: N, inline: N)218- **Comment density:** N comments per 100 LOC219- **Type distribution:** Type 1: N, Type 2: N, ... Type 9: N220- **Quality score:** N/10221222### Critical Gaps223- [ ] {file}:{line} - {element} - Missing {type} comment - {impact}224225### Issues Found226#### Negative Comments (fix or remove)227- {file}:{line} - Type {N} ({name}) - "{comment text}" - Action: {delete/resolve/rewrite}228229#### Outdated Comments230- {file}:{line} - "{comment text}" - Mismatch: {description}231232#### Quality Issues233- {file}:{line} - Type {N} - Issue: {description}234235### Coverage Metrics236| Scope | With Docstring | Without | Coverage |237|-------|---------------|---------|----------|238| Modules | N | N | N% |239| Classes | N | N | N% |240| Public functions | N | N | N% |241| Public methods | N | N | N% |242243### Recommendations2441. **Priority 1:** {action} - {N elements affected}2452. **Priority 2:** {action} - {N elements affected}2463. **Priority 3:** {action} - {N elements affected}247248### Comment Style249- **Detected style:** {Google/NumPy/Sphinx/mixed}250- **Consistency:** {consistent/inconsistent}251- **Recommendation:** {standardize on X style}252```253254See `references/examples/audit-mode-examples.md` for complete report examples.255256## Key Constraints257258- **NEVER add trivial comments** - If the code says `x += 1`, do not add `# increment x`259- **NEVER add placeholder docstrings** - `"""Process data."""` on a complex function is worse than nothing260- **NEVER duplicate type hints** - If type hints exist, document semantics not types261- **NEVER change code logic** - Comments and docstrings only, zero functional changes262- **PRESERVE existing style** - Match the project's existing docstring style263- **PRESERVE valid comments** - Only modify/delete comments that are negative types (7-9) or demonstrably wrong264265## Integration with Same-Package Skills266267- **python-refactor** - Refactoring may require updating comments. Run write mode after refactoring to update docstrings268- **python-tdd** - Test docstrings benefit from type 1 (function) comments. Audit mode can assess test documentation269- **python-performance-optimization** - Performance-critical code benefits from type 4 (teacher) comments explaining algorithm choices270- **python-packaging** - Package-level documentation (`__init__.py` docstrings) follows type 1+2 patterns