Example result: Add helpful comments and docstrings to code
AI-generated example · Code Comments
Updated

Add helpful comments and docstrings to code

This prompt adds clear comments and docstrings to your code, focusing on why it does things.

text-write-code-comments — chatgpt — 44 words

Add clear comments and docstrings to this code:

[PASTE CODE]

Explain why decisions were made, not what each line does. Document parameters, return values, side effects and exceptions. Flag anything confusing or risky without changing the logic, and list any names you would rename.

Ask it to explain why, not what; comments that repeat the code are noise.

Get a better result

What you will get

Your code with comments that explain why decisions were made, docstrings covering parameters, return values, side effects and exceptions, notes on anything risky, and a list of names worth renaming.

Why it works

Good comments explain intent, which the code cannot show, so the prompt asks for why rather than what. Docstrings for parameters, returns, side effects and exceptions are the details a future reader needs most. Flagging risky parts without changing logic keeps the change safe to review.

Common mistake

The comments repeat what each line does.

Fix: As the tip says, ask for why, not what. A comment like “increment i” is noise.

Also watch for
  • It guesses reasons for decisions it cannot know. Add a line of context, such as why a workaround exists. Otherwise ask it to mark guesses with a question.
  • The logic changes slightly. The prompt says not to change it. Compare the files with a diff and reject any change outside comments.
Try a variation: module overview

Ask for a short overview comment at the top of the file explaining what the module is for, its main entry point and what it depends on.

Still not right? Reply with this

Remove every comment that only restates the code, and turn the risky parts you flagged into warning comments with a one-line reason each.

More chat & writing prompts

See all 465 →