You know you should document your code and write tests. You also know it's late, the feature has to ship, and those two jobs always get pushed to "later."
Later never comes. So let AI write the first draft while you do the part that matters: reviewing it.
In this post you'll build a small Python script that takes any .py file and gives you:
- a copy with clean docstrings added (your code untouched)
- a ready-to-run pytest file
- an automatic test run, so you see results in seconds
It takes about 5 minutes to set up. (If you want the full workflow for whole projects, there's a link at the end.)
Setup
pip install anthropic pytest
export ANTHROPIC_API_KEY="your-key"
The script
# ai_docs_tests.py
import pathlib
import subprocess
import sys
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
MODEL = "claude-sonnet-5-5" # swap for any model you have access to
FENCE = "`" * 3 # three backticks, built this way so it can't break the page
DOC_PROMPT = """Add Google-style docstrings to every function and class in this
Python file. Do NOT change any code. Return only the full file, no commentary.
{code}"""
TEST_PROMPT = """Write pytest tests for this module (import it as `{module}`).
Cover normal cases, edge cases, and expected errors. Return only the test file.
{code}"""
def ask(prompt: str) -> str:
resp = client.messages.create(
model=MODEL,
max_tokens=4000,
messages=[{"role": "user", "content": prompt}],
)
return strip_fences(resp.content[0].text)
def strip_fences(text: str) -> str:
lines = [l for l in text.strip().splitlines() if not l.strip().startswith(FENCE)]
return "\n".join(lines) + "\n"
def main(path: str) -> None:
src = pathlib.Path(path)
if not src.exists():
sys.exit(f"File not found: {path}")
code = src.read_text()
documented = ask(DOC_PROMPT.format(code=code))
src.with_suffix(".documented.py").write_text(documented)
tests = ask(TEST_PROMPT.format(module=src.stem, code=code))
test_path = src.parent / f"test_{src.stem}.py"
test_path.write_text(tests)
subprocess.run([sys.executable, "-m", "pytest", "-q", str(test_path)])
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("Usage: python ai_docs_tests.py <file.py>")
main(sys.argv[1])
Run it:
python ai_docs_tests.py utils.py
Your original file is never overwritten. You get utils.documented.py and test_utils.py, and pytest runs right away.
What it looks like
Say utils.py contains this:
def apply_discount(price, percent):
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)
You'll get a documented version along these lines (exact output varies by model):
def apply_discount(price, percent):
"""Apply a percentage discount to a price.
Args:
price (float): The original price.
percent (float): Discount percentage, from 0 to 100.
Returns:
float: The discounted price, rounded to 2 decimal places.
Raises:
ValueError: If percent is outside the range 0 to 100.
"""
...
And tests like these:
import pytest
from utils import apply_discount
def test_normal_discount():
assert apply_discount(100, 20) == 80.0
def test_zero_and_full_discount():
assert apply_discount(50, 0) == 50.0
assert apply_discount(50, 100) == 0.0
def test_invalid_percent():
with pytest.raises(ValueError):
apply_discount(100, 120)
That's a few minutes of typing you didn't do.
4 rules that keep this safe
- Always read the output. AI tests can pass while testing nothing meaningful. Check that each assertion matches what the function should really do.
- Diff the documented file against your original to confirm no code changed.
- Give the prompt context. Add a line like "this function validates Nigerian phone numbers" and the tests get far better.
- Save the prompts that work. A good prompt library saves hours every month.
Where this simple script runs out
Being honest, this script is a starting point. It struggles when:
- your file is too big for one request
- your code depends on other modules, databases, or APIs
- you want docs and tests to run automatically for a whole project, not one file at a time
- the generated tests are shallow and you don't know how to push the AI for better ones
Solving those is a workflow problem, not a script problem. That's exactly what I built my course around.
Want the full workflow?
AI for Developers: Automate Documentation & Testing + Real Project shows you step by step how to:
- generate documentation automatically
- write clean, readable docstrings
- generate and run unit tests with AI
- automate your workflow end to end
- build a real project where docs and tests are produced for you
It's straight to the point, fully practical, and beginner-friendly. You also get reusable AI prompts and workflow ideas you can apply right away.
Who it's for: beginners learning programming, developers who hate writing documentation, and anyone who wants to work faster with AI.
Two options:
- Basic ($9): the full course, all modules, and the real project.
- Premium (Most Popular): everything in Basic, plus 5 premium PDFs: an AI Prompt Pack, Workflow Cheat Sheet, Fast-Track Guide, and Complete Project Guide.
Quick recap
- Use AI to draft docstrings and tests, and keep the human review.
- Never overwrite your original files.
- Start with the script above, then grow it into a full workflow.
If this saved you time, drop a ❤️ and share it with a developer friend who hates writing docs. Questions? Ask in the comments and I'll answer.
Top comments (0)