How to Write Docs with AI
Good docs explain how to use the code, not how clever it looks. Ask the AI for docstrings, README steps and “why” notes — then check every command against reality.
In short: point the AI at the real function or script, ask for audience + format, verify commands by running them, and never invent product URLs or version numbers.
Why AI helps with docs
Writing first drafts is slow. AI turns a function into a clear docstring or a short README section quickly. It also invents flags that do not exist. Your job is to run the commands and fix the lies.
What to ask for
- Docstring / JSDoc / XML doc: inputs, outputs, errors, one example.
- README section: install → run → test, in vertical steps.
- Changelog / PR summary: what changed and why, in plain English.
- Audience: beginner teammate vs API consumer — say which.
How writing docs flows
Example: docstring for EMI
Add a clear Python docstring to monthly_emi. Include formula in one line, Args, Returns, Raises. Keep the code logic unchanged. Easy English.
def monthly_emi(principal: float, annual_rate_percent: float, months: int) -> float:
"""Return EMI for a reducing-balance loan.
Formula: EMI = P * r * (1+r)^n / ((1+r)^n - 1)
where r is the monthly rate (annual_rate_percent / 12 / 100).
Args:
principal: loan amount in rupees (must be > 0).
annual_rate_percent: yearly interest, e.g. 10 for 10%.
months: tenure in months (must be > 0).
Returns:
EMI rounded to 2 decimal places.
Raises:
ValueError: if principal or months is not positive.
"""
if principal <= 0 or months <= 0:
raise ValueError("principal and months must be > 0")
if annual_rate_percent == 0:
return round(principal / months, 2)
r = annual_rate_percent / 12 / 100
factor = (1 + r) ** months
return round(principal * r * factor / (factor - 1), 2)How to write docs step by step
- Open the real file in the IDE so the AI sees current signatures.
- Say the format: Google-style docstring, JSDoc, or “README steps only”.
- Ban marketing language. Ask for verbs: Install, Run, Test.
- Run every shell command the draft suggests. Delete what fails.
- Keep docs next to the change so they do not rot.
| Doc type | Good ask |
|---|---|
| Function docstring | “Args, Returns, Raises, one example; no essay.” |
| README quickstart | “5 vertical steps: clone, install, env, run, test.” |
| API note | “Request shape + error codes we actually return.” |
| Internal ADR | “Context, decision, consequences — one page.” |
Settings tip
- Project rules: “Docs must match real CLI flags; prefer short steps.”
- For README work, paste package.json / pyproject scripts so versions stay honest.
- Prefer a careful model for long docs; use a fast model for one-line comment cleanup.
Try this yourself: write docs with AI, then prove them with tests
Hello friends. In this practice you keep a small working function, ask an AI assistant for a Google-style docstring and a short README, and then you prove both with pytest. The names Mira Quill and peplin moss are fictional practice data only. If the AI invents a CLI flag you never ran, you must delete that line before you publish the docs.
नमस्कार मित्रांनो. या सरावात तुम्ही एक छोटा काम करणारा function ठेवता, AI कडून Google-style docstring आणि छोटी README मागता, आणि नंतर pytest ने दोन्ही सिद्ध करता. Mira Quill आणि peplin moss ही फक्त काल्पनिक सराव नावे आहेत. AI ने असा CLI flag लिहिला जो तुम्ही कधी चालवला नाही, तर तो ओळ प्रकाशित करण्याआधी तुम्ही तो डिलीट करायलाच हवा.
नमस्ते दोस्तों. इस अभ्यास में आप एक छोटा काम करने वाला function रखते हो, AI से Google-style docstring और छोटी README मांगते हो, और फिर pytest से दोनों साबित करते हो. Mira Quill और peplin moss सिर्फ काल्पनिक अभ्यास नाम हैं. अगर AI ने ऐसा CLI flag लिखा जो आपने कभी चलाया ही नहीं, तो docs प्रकाशित करने से पहले वह पंक्ति जरूर हटाओ.
Ravindra Bagale's Tip
Never publish a README command you have not run yourself. AI assistants often invent flags like --magic-format. Keep only the commands that actually work on your machine.
Ravindra Bagale's Tip – मराठी
जी README command तुम्ही स्वतः चालवली नाही, ती कधीच प्रकाशित करू नका. AI अनेकदा --magic-format सारखे flags शोधून काढते. फक्त तुमच्या मशीनवर खरोखर चालणाऱ्या commands ठेवा.
Ravindra Bagale's Tip – हिंदी
जो README command आपने खुद नहीं चलाई, उसे कभी प्रकाशित मत करो. AI अक्सर --magic-format जैसे flags गढ़ लेती है. सिर्फ वही commands रखो जो आपकी मशीन पर सच में चलती हैं.
Python 3.13.5 and pytest 9.2.0. Use Python 3.10 or newer. Older Python versions print the traceback with fewer ^^^ marker lines, but the last line with the error type and message is the same.Your task: you already have a working fictional helper format_rupee(amount) that prints Indian Rupee amounts with the ₹ symbol and two decimals, raises ValueError for negatives, and raises TypeError for non-numeric values (including bool). Ask an AI assistant for a Google-style docstring and a short README with Run and Test steps. Then run the tests below. Behaviour tests must keep passing, and the docstring tests must start passing only after the docstring is real. Finally delete any invented CLI flag from the README draft.
Setup
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - Activate it: on macOS or Linux run
source .venv/bin/activate. In Windows Command Prompt run.venv\Scripts\activate.bat, and in Windows PowerShell run.venv\Scripts\Activate.ps1. - Install pytest inside the virtual environment:
python -m pip install pytest.
Starter rupee.py (behaviour works, docstring is missing on purpose):
"""Fictional practice module for formatting Indian Rupee amounts (teaching data only)."""
def format_rupee(amount):
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
raise TypeError("amount must be an int or float")
if amount < 0:
raise ValueError("amount must not be negative")
return f"₹{amount:.2f}"
Tests test_rupee.py (do not weaken these checks):
"""Behaviour + docstring checks for the fictional format_rupee helper."""
import pytest
from rupee import format_rupee
def test_formats_positive_amount():
assert format_rupee(12.5) == "₹12.50"
assert format_rupee(0) == "₹0.00"
assert format_rupee(100) == "₹100.00"
def test_rejects_negative_amount():
with pytest.raises(ValueError, match="negative"):
format_rupee(-1)
def test_rejects_non_numeric():
with pytest.raises(TypeError, match="int or float"):
format_rupee("12.5")
with pytest.raises(TypeError, match="int or float"):
format_rupee(True)
def test_docstring_has_args_and_returns():
doc = format_rupee.__doc__
assert doc is not None, "format_rupee must have a docstring"
lower = doc.lower()
assert "args" in lower or "arguments" in lower
assert "returns" in lower
def test_docstring_mentions_raises():
doc = format_rupee.__doc__
assert doc is not None
assert "raise" in doc.lower()
Draft README with a deliberate AI lie (the --magic-format line is fake — delete it after you verify real commands):
# peplin moss rupee helper (fictional practice)
Tiny teaching module used by Mira Quill's demo shop ledger (not a real shop).
## Run
```bash
python -c "from rupee import format_rupee; print(format_rupee(12.5))"
```
## Test
```bash
python -m pytest -q test_rupee.py
```
## Fake AI draft line (DELETE after you verify)
```bash
python -m peplin_moss --magic-format 12.5
```
That `--magic-format` flag does **not** exist. An AI invented it. Delete it from any README you publish.
Suggested AI ask (copy and adapt):
docs-prompt.txtAdd a Google-style docstring to format_rupee in rupee.py with Args, Returns and Raises. Also draft a short README with only Run and Test steps that match these real commands: python -c "from rupee import format_rupee; print(format_rupee(12.5))" and python -m pytest -q test_rupee.py. Do not invent CLI flags. Fictional practice only.
HOW to finish
- Save
rupee.pyandtest_rupee.pyin your project folder. - Run
python -m pytest -q test_rupee.py. Expect 2 failed, 3 passed while the docstring is still missing. - Ask your AI assistant for the Google-style docstring and a short honest README.
- Paste the docstring into
rupee.pyand save. Keep the function body unchanged. - Run the same pytest command again. Expect 5 passed.
- Open the README draft and delete any invented flag such as
--magic-format. Keep only commands you actually ran. - Optional manual check:
python -c "from rupee import format_rupee; print(format_rupee(12.5))"should print₹12.50.
Real output before the docstring:
pytest-before.txt2 failed, 3 passed in 0.01s
Real output after a good docstring (seconds can differ slightly):
pytest-after.txt..... [100%]
5 passed in 0.00s
Optional documented rupee.py and cleaned README (try it yourself first)
Your AI assistant may word the docstring differently. Any version is fine if all 5 tests pass and the README has no invented flags.
rupee.py"""Fictional practice module for formatting Indian Rupee amounts (teaching data only)."""
def format_rupee(amount):
"""Format a non-negative amount as an Indian Rupee money string.
Args:
amount: An int or float that is zero or greater. Booleans are rejected.
Returns:
A string that starts with the ₹ symbol and shows exactly two decimal places,
for example '₹12.50' or '₹0.00'.
Raises:
TypeError: If amount is not an int or float (including bool).
ValueError: If amount is negative.
"""
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
raise TypeError("amount must be an int or float")
if amount < 0:
raise ValueError("amount must not be negative")
return f"₹{amount:.2f}"
README.md# peplin moss rupee helper (fictional practice)
Tiny teaching module used by Mira Quill's demo shop ledger (not a real shop).
## Run
```bash
python -c "from rupee import format_rupee; print(format_rupee(12.5))"
```
## Test
```bash
python -m pytest -q test_rupee.py
```
Troubleshooting
- Problem: docstring tests still fail after you paste AI text. Fix: the docstring must sit immediately under
def format_rupeeas a triple-quoted string, and it must clearly include Args (or Arguments), Returns, and Raises. - Error:
ModuleNotFoundError: No module named pytest. Fix: activate the virtual environment and runpython -m pip install pytest. - Problem: behaviour tests fail after editing. Fix: you changed the function body; restore the starter logic and only edit the docstring.
- Problem: the README still shows
--magic-format. Fix: delete that whole command line. That flag does not exist in this practice project.
Practice cards: English and spoken Marathi
Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.
Docs are code you must verify
Docstring checks catch empty docs
Docs म्हणजे verify करायचा code
Docstring checks रिकाम्या docs पकडतात
Quick quiz
1. What must you verify in AI docs?
Every command, flag and version against the real project.
2. What belongs in a docstring?
Inputs, outputs, errors, and a small example — not a blog post.
3. Where should docs live relative to a change?
In the same PR / commit when possible.
4. What tone works best?
Short, plain English verbs.
Save tokens and money
Generate one section at a time (Quickstart, then Config). Huge “document the whole monorepo” prompts waste tokens and invent details.