The best AI prompts for code comments ask the model to explain why the code does something, not what each line does, and they supply the context the model cannot see: the business rule, the bug being worked around, the units, the caller’s expectations. Docstrings are a separate job with a separate prompt, because they document the interface (arguments, return value, errors) in a fixed format your tools can read. This article gives one prompt for each job, a cleanup prompt for over-commented code, and a before/after example you can compare against your own output.
Comments, docstrings and inline documentation are different jobs
Most bad AI-generated documentation comes from treating these as one task. They answer different questions for different readers:
| Type | Question it answers | Reader | Where it shows up |
|---|---|---|---|
| Docstring / doc comment (e.g. Python docstring, JSDoc, Javadoc) | How do I call this, and what do I get back? | Anyone calling the function, often without opening the file | IDE hover, generated reference docs, help() |
| Block comment | Why does this section work this way? | The next person changing the code | Only in the source file |
| Inline comment | What is non-obvious about this one line? | Same as above | Only in the source file |
| TODO / FIXME | What is known to be incomplete, and where is it tracked? | Maintainers | Source, and often issue trackers |
Python’s PEP 257 says a function docstring should cover behavior, arguments, return values, side effects, exceptions raised, and restrictions on when the function can be called. The Google Python Style Guide is blunter about block and inline comments: use them for tricky code and “never describe the code.” Those two rules are the backbone of the prompts below.
Why models over-comment by default
A model asked to “add comments to this code” tends to narrate it, because narrating is the only thing it can do with confidence from the code alone. It sees retries += 1 and writes “increment the retry counter”. It cannot know that the retry limit is 3 because a payment provider bans clients after the fourth failed attempt; that fact lives in someone’s head or a ticket.
So the problem is not that AI writes bad comments. It is that you asked for comments without supplying the information comments exist to carry. Fix the input and the output changes.
Prompt 1: Comments that explain why
Use this when a function works but the next person will not understand its decisions. The context section is the part people skip and the part that matters most.
Add comments to the code below for a developer who knows [language]
well but has never seen this codebase.
## Context the code does not show
- Business rule(s): [e.g. "refunds over 30 days need manager approval"]
- Workarounds: [e.g. "vendor API returns 200 with an error body"]
- Units / formats: [e.g. "amounts are integer cents", "timestamps UTC"]
- Why the obvious approach was not used: [if any]
- Known limitations: [if any]
## Rules
1. Comment only where a competent reader would otherwise ask "why?".
Do not comment lines whose purpose is clear from the code.
2. Never restate what the code does. If a comment would still make
sense with the code beneath it deleted, it is describing WHAT;
rewrite it to explain WHY or remove it.
3. Use only facts from the context above or directly visible in the
code. If a decision looks deliberate but the reason is not given,
add `# REASON?` at that line instead of inventing one.
4. Keep comments short; full sentences, no decorative banners.
5. Do not change any code.
Return the full code with comments added, then a list of the
`# REASON?` markers you left.
```[language]
[paste code]
```
Rule 3 is the safety net. Without it, a model asked to explain “why” will happily invent a reason, and a plausible but wrong comment is worse than none because people trust it. The # REASON? markers turn the model into a reviewer that points at undocumented decisions, which is often more valuable than the comments themselves. The same “say what you do not know” pattern is covered in reducing AI hallucinations with better prompts.
Rule 2 gives the model a test it can apply to its own output. “Would this comment still make sense with the code deleted?” catches nearly all narration, because narration is just the code in English.
Prompt 2: Docstrings in your project’s format
Docstrings have a fixed structure, so the prompt should name the format and, ideally, include one existing docstring from your codebase as a style sample. Models reproduce an example much more faithfully than a description.
Write a docstring for the function below.
Format: [Google-style Python | NumPy-style | reStructuredText |
JSDoc | Javadoc | TSDoc]. Match this existing example from our
codebase exactly in structure and tone:
```
[paste one good docstring from your repo]
```
Requirements:
- First line: one-sentence summary in the imperative ("Return...",
"Create..."), ending with a period.
- Document every parameter: meaning, units, allowed range or values,
and what happens with None/null/empty.
- Document the return value, including the empty or not-found case.
- List exceptions the caller should expect and when each is raised.
Only list exceptions that the code actually raises or lets
propagate; do not guess.
- Mention side effects (writes, network calls, mutation of inputs).
- Do not describe the implementation.
- If the type hints and the code disagree, point it out after the
docstring instead of picking one.
```[language]
[paste function, plus any custom exception classes it raises]
```
The imperative summary line follows PEP 257, which asks for a phrase like “Return the pathname” rather than “Returns the pathname”. The “only list exceptions the code actually raises” requirement prevents a common failure where a model adds Raises: ValueError to every function because many functions raise it. The last requirement turns docstring writing into a light review: mismatches between hints and behavior are real bugs.
For JavaScript, name JSDoc’s conventions explicitly if your tools depend on them. The JSDoc @param reference uses [name] for optional parameters, [name=value] for defaults, and dotted names such as options.timeout to document properties of an object parameter. Models sometimes mix in TypeScript-only syntax, so ask for whichever one your build reads.
Prompt 3: Clean up over-commented code
Legacy code and earlier AI output are often full of narration. This prompt removes it without losing the comments that carry real information.
Review the comments in this code. Do not change any code.
Classify every comment as one of:
- KEEP: explains a reason, constraint, workaround, unit, or edge case
that is not obvious from the code.
- REWRITE: has useful information but is unclear, outdated, or wrong
relative to the current code. Give the rewritten text.
- DELETE: restates what the code does, is commented-out code, or is
a stale TODO with no ticket reference.
Flag any comment that CONTRADICTS the code as high priority; those
are the most dangerous.
Output a table (line | current comment | action | new text or
reason), then the cleaned code.
```[language]
[paste code]
```
Asking for a classification table before the cleaned code lets you review the decisions rather than diffing the whole file. The contradiction flag is the most useful output: a comment that says “amounts in dollars” above code that clearly handles cents is a bug report in disguise. If the cleanup is part of a larger restructuring, pair it with the prompts in AI prompts for refactoring legacy code.
Before and after: the same function, two prompts
Here is an illustrative Python function from a fictional billing service, first with the kind of comments a bare “add comments” prompt typically produces.
# Before: narration
def charge_with_retry(client, invoice_id, amount_cents):
# Set retries to 0
retries = 0
# Loop while retries is less than 3
while retries < 3:
# Call the charge API
resp = client.charge(invoice_id, amount_cents)
# Check if the response body has an error
if resp.json().get("error") is None:
# Return the response
return resp
# Increment retries
retries += 1
# Sleep
time.sleep(2 ** retries)
# Raise an exception
raise ChargeFailed(invoice_id)
Every comment is true and none is useful. Now the same function after Prompt 1 and Prompt 2, given this context: the provider returns HTTP 200 with an error field on declined charges; the provider blocks a client after four failed attempts on the same invoice; amounts are integer cents.
# After: why, plus an interface docstring
def charge_with_retry(client, invoice_id, amount_cents):
"""Charge an invoice, retrying failed attempts with backoff.
Args:
client: Payment provider client.
invoice_id: Provider invoice ID to charge.
amount_cents: Amount in integer cents (not dollars).
Returns:
The provider response for the first successful charge.
Raises:
ChargeFailed: If all 3 attempts fail.
"""
retries = 0
# Max 3 attempts: the provider blocks the client after the 4th
# failed attempt on the same invoice.
while retries < 3:
resp = client.charge(invoice_id, amount_cents)
# The provider returns HTTP 200 even for declines; the only
# failure signal is the "error" field in the body.
if resp.json().get("error") is None:
return resp
retries += 1
time.sleep(2 ** retries) # REASON? backoff values not specified
raise ChargeFailed(invoice_id)
Three things changed. The comments now carry facts that were not in the code (the ban threshold, the misleading status code). The docstring documents units and the failure mode for callers who will never open the file. And the # REASON? marker shows that nobody recorded why the backoff is exponential with those values, which is a question worth asking the team.
Review checklist for AI-written comments
Read every generated comment as if a new colleague wrote it, and check these before committing:
- Is every stated reason true? If you cannot confirm a “because”, delete it or turn it into a question for the author.
- Does it match the current code? Comments generated from an older version of a function are a common source of contradictions.
- Are units and formats explicit? Cents versus dollars, seconds versus milliseconds, UTC versus local time.
- Do docstring exceptions match reality? Search the function for
raiseorthrowand compare. - Are TODOs tracked? The Google Python Style Guide recommends a TODO format with a reference such as a bug link, rather than a person’s name. An untracked TODO is a note nobody will read.
- Is anything sensitive in it? Comments sometimes pick up internal hostnames, customer names or credentials from the context you pasted.
This review fits naturally into code review. If your team already uses an AI review step, add “flag comments that restate the code or contradict it” to the instructions; see AI code review prompts for a full setup.
Making it consistent across a team
Prompts in individual chat windows drift. If your team uses an AI coding assistant, put the comment rules in the assistant’s project instruction file so they apply to every request without anyone pasting them. For GitHub Copilot that is a repository instructions file; the Copilot instructions file checklist shows how to write one people will follow. A short block is enough:
## Comments and docstrings
- Comments explain why, never what. No comments on self-explanatory lines.
- Never invent a reason; mark unknown reasons with `# REASON?`.
- Public functions get Google-style docstrings (Args, Returns, Raises).
- Units must be explicit for money, time and sizes.
- TODOs must reference a ticket: `# TODO(PROJ-123): ...`
Inline comments and docstrings cover the code level. Higher-level documentation, such as how to install and run the project or how to call its HTTP endpoints, needs different prompts: see AI prompts for README files and project documentation.



