Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 5 · WORKFLOWS

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

WHY

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

WHAT
  • 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

1 · Point at real code @file or paste 2 · Name audience + format docstring / README 3 · Draft from AI short, plain English 4 · Run every command fix inventions 5 · Commit docs with code same PR when possible

Example: docstring for EMI

DOCSTRING PROMPT (COPY)

Add a clear Python docstring to monthly_emi. Include formula in one line, Args, Returns, Raises. Keep the code logic unchanged. Easy English.

emi.py (with docstring)
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

HOW
  1. Open the real file in the IDE so the AI sees current signatures.
  2. Say the format: Google-style docstring, JSDoc, or “README steps only”.
  3. Ban marketing language. Ask for verbs: Install, Run, Test.
  4. Run every shell command the draft suggests. Delete what fails.
  5. Keep docs next to the change so they do not rot.
Doc typeGood 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.”
Rule: if you did not run the command, do not publish it. AI often invents flags like --magic that your CLI does not have.

Settings tip

  1. Project rules: “Docs must match real CLI flags; prefer short steps.”
  2. For README work, paste package.json / pyproject scripts so versions stay honest.
  3. 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.

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.

Practice label: every name, number and time in this exercise is fictional teaching data. It is not about a real person, account or company. Passing these tests proves only the cases listed in the tests, not every possible input.
Environment (tested): this exercise was run on 6 November 2026 with 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

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. 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.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Starter rupee.py (behaviour works, docstring is missing on purpose):

rupee.py
"""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):

test_rupee.py
"""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):

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
```

## 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.txt
Add 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

HOW
  1. Save rupee.py and test_rupee.py in your project folder.
  2. Run python -m pytest -q test_rupee.py. Expect 2 failed, 3 passed while the docstring is still missing.
  3. Ask your AI assistant for the Google-style docstring and a short honest README.
  4. Paste the docstring into rupee.py and save. Keep the function body unchanged.
  5. Run the same pytest command again. Expect 5 passed.
  6. Open the README draft and delete any invented flag such as --magic-format. Keep only commands you actually ran.
  7. 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.txt
2 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

HOW
  1. Problem: docstring tests still fail after you paste AI text. Fix: the docstring must sit immediately under def format_rupee as a triple-quoted string, and it must clearly include Args (or Arguments), Returns, and Raises.
  2. Error: ModuleNotFoundError: No module named pytest. Fix: activate the virtual environment and run python -m pip install pytest.
  3. Problem: behaviour tests fail after editing. Fix: you changed the function body; restore the starter logic and only edit the docstring.
  4. 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.

PRACTICE CARDAI Coding

Docs are code you must verify

Ask the AI for a Google-style docstring and short Run/Test steps.
Run pytest yourself. Keep only commands that really work, and delete invented flags.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Docstring checks catch empty docs

These tests look for Args and Returns wording inside the function docstring.
When all 5 tests pass, the docs and the behaviour agree on the cases you listed.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Docs म्हणजे verify करायचा code

AI कडून Google-style docstring आणि छोटी Run/Test steps मागा.
pytest स्वतः चालवा. फक्त खरोखर चालणाऱ्या commands ठेवा, आणि शोधून काढलेले flags डिलीट करा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Docstring checks रिकाम्या docs पकडतात

हे tests function docstring मध्ये Args आणि Returns शब्द शोधतात.
जेव्हा सगळ्या 5 tests पास होतात, तेव्हा docs आणि behaviour तुम्ही लिहिलेल्या cases वर जुळतात.
Ravindra Bagale · ravindrabagale.com/ai-coding

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

SMART AI USE

Generate one section at a time (Quickstart, then Config). Huge “document the whole monorepo” prompts waste tokens and invent details.

Save these cards

INTERVIEW CARDAI Coding

How do you write docs with AI?

Point at real code, set audience and format.
Run every command; delete inventions.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Docstring vs README

Docstring: how to call one function.
README: how to run the project end to end.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Docs in 3

Real code in context.
Short draft.
Verify commands.
Ravindra Bagale · ravindrabagale.com/ai-coding