Coding
AI Prompt for Writing Code Comments
Add meaningful code comments with this AI prompt: explains the why behind tricky code, skips the obvious, and flags what needs refactoring instead.
The prompt
Role: You are a senior developer who writes comments that future maintainers are grateful for.
Context: Language: [LANGUAGE]. Comment philosophy: [PHILOSOPHY: explain WHY, not WHAT]. Density: [DENSITY: only the non-obvious / thorough].
Code:
[CODE]
Task: 1) Add comments to the code following [PHILOSOPHY]: explain intent, non-obvious decisions, tricky algorithms, and warnings — never restate what the code obviously does. 2) Return the fully commented code. 3) List what you deliberately left UNcommented and why (self-evident code needs no comments). 4) Flag any code so confusing that it needs refactoring, not commenting.
Format: Commented code first, then the deliberately-uncommented list, then the needs-refactoring flags.
Ask the AI to date-stamp any comment that explains a temporary workaround, with the condition for removing it. Workarounds without expiry dates become permanent mysteries.
Constraints: No noise comments ("increment i", "return result"). Every comment must earn its place by explaining something the code does not say. Keep comments current with the code — note where comments would rot if the code changes.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [PHILOSOPHY] [DENSITY] [CODE]
Example input
LANGUAGE=Python, CODE=data pipeline script with zero comments, STYLE=explain WHY not WHAT, DENSITY=comment the non-obvious 20%
How to use this prompt
Specify the density and philosophy — 'why not what' is the professional standard. Point at the trickiest section if the file is long.
Tips for the best results
- Delete any comment that just restates the code — the AI sometimes adds a few; prune them.
- Ask it to flag 'needs refactoring' honestly; comments cannot fix confusing code.
- Review comments after your next change; stale comments are worse than none.
Frequently asked questions
Won't it just comment every line?
It comments the why and the non-obvious, and explicitly skips the obvious — then tells you what it left uncommented and why.
How do I keep comments from going stale?
Comment the why, which changes slower than the what — and review comments in every refactor. The prompt's audit mode finds stale ones automatically.