Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/10-documentation/10-documentation.ipynb

View source on GitHub

Module 10: Documentation & Communication#

AI-assisted documentation for your code.

Learning Objectives#

  1. Write effective docstrings

  2. Create README files

  3. Generate API documentation

  4. Use AI for documentation tasks

Why Documentation?#

  • Future you will thank present you

  • Others can use your code

  • Forces clarity of thought

  • Required for open source

AI makes documentation much easier!

Docstrings#

Google style:

def search_works(query: str, limit: int = 10) -> list[dict]:
    """Search OpenAlex for scholarly works.
    
    Args:
        query: Search query string.
        limit: Maximum number of results.
    
    Returns:
        List of work dictionaries with title, year, citations.
    
    Raises:
        ValueError: If query is empty.
        APIError: If the API request fails.
    
    Examples:
        >>> search_works("machine learning", limit=5)
        [{'title': '...', 'year': 2024, ...}, ...]
    """

Context Engineering Reminder (from Module 00)

Before starting this exercise, think about what context the agent needs. For documentation, that means:

  • Have the agent read the source code before writing docstrings — it needs to see parameter types, return values, and logic

  • Show it an example of your preferred docstring style (numpydoc, Google, Sphinx) or point to an existing docstring in the project

  • For READMEs, load pyproject.toml and a sample usage script so the agent can describe accurate installation and usage

Load the context first, then ask for the action.

Exercise 1: Write a Docstring (5 min)#

Practice writing a Google-style docstring by hand before using AI.

  1. Write a docstring for this function (without AI help first):

    def filter_by_year(works, start_year, end_year=None):
        # filters works list to only include those published
        # between start_year and end_year (inclusive)
        ...
    

    Include all of these sections:

    • Summary (one line)

    • Args (with types for works, start_year, end_year)

    • Returns (what type and what it contains)

    • Raises (what errors could occur?)

    • Example (a short usage example)

  2. Now ask your AI agent to write a docstring for the same function.

  3. Compare the two. Consider:

    • Whose is more accurate?

    • Did the AI assume things about the function that might be wrong?

    • Did you forget any sections that the AI included?

Expected outcome: You can write a complete Google-style docstring from memory, and you understand where AI drafts need human verification.

AI-Generated Docstrings#

> Add comprehensive docstrings to this module:
  [paste code]
  
  Use Google style. Include:
  - Description
  - Args with types
  - Returns
  - Raises
  - Examples

AI generates docstrings for all functions - review for accuracy!

Exercise 2: AI Docstring Audit (10 min)#

Use AI to draft docstrings, then critically review them — a realistic professional workflow.

  1. Pick 3 functions from your course project (or from any Python module you’ve written). Choose functions that currently lack docstrings.

  2. Ask your AI agent to add docstrings to all of them:

    “Add Google-style docstrings to these functions: [paste your code]”

  3. Review each generated docstring. For each one, check:

    • Is the description accurate? (AI sometimes guesses wrong about what a function does)

    • Are the parameter types correct?

    • Are the return types correct?

    • Are the examples actually runnable? (Try them!)

    • Is anything important missing?

  4. Fix any issues you find. Common AI mistakes:

    • Incorrect type annotations (e.g., saying list when it’s actually dict)

    • Examples that don’t match the actual function signature

    • Missing edge cases in the description

Expected outcome: You have 3 functions with reviewed, accurate docstrings. You’ve practiced the “AI drafts, human reviews” workflow that’s standard in industry.

README#

Essential sections:

# Package Name

Brief description.

## Installation

```bash
pip install package-name

Quick Start#

from package import function
result = function("example")

Features#

  • Feature 1

  • Feature 2

License#

MIT


Ask AI to generate from your code!

Exercise 3: README from Scratch (10 min)#

Write a concise, effective README for your project.

  1. Create (or rewrite) your project’s README.md with these sections:

    • Project title

    • One-line description (what does it do?)

    • Installation instructions (pip install ... or git clone ...)

    • Quick usage example (3-5 lines of working Python code)

    • Link to documentation (if you have any, or “Coming soon”)

  2. Keep it under 30 lines. A good README is concise. You can always add more later.

  3. Ask your AI agent to review it:

    “Is this README clear enough for a new user who has never seen my project? What’s missing?”

  4. Revise based on the feedback. Common things people forget:

    • What Python version is required?

    • What are the dependencies?

    • A real, copy-pasteable example

Expected outcome: You have a clean, professional README that a stranger could follow to install and use your package.

API Documentation#

Use Sphinx or MkDocs to generate docs from docstrings:

pip install sphinx sphinx-autodoc-typehints
sphinx-quickstart docs
sphinx-build docs docs/_build

Or with MkDocs:

pip install mkdocs mkdocstrings[python]
mkdocs new .
mkdocs serve

Exercise 4: Generate API Docs (10 min)#

See what auto-generated documentation looks like for your code.

Option A: Using pdoc (quick and easy)

  1. Install pdoc:

    pip install pdoc
    
  2. Generate HTML docs for your package:

    pdoc your_package_name --html -o docs/
    

    (Replace your_package_name with your actual package name)

  3. Open the generated HTML file in your browser. Explore it:

    • Are all your functions listed?

    • Do functions without docstrings look sparse?

    • How do the docstrings you wrote in Exercise 2 look in the rendered docs?

Option B: Using AI (if pdoc doesn’t work for your setup)

  1. Ask your AI agent:

    “Generate markdown API documentation for these functions: [paste your module code]”

  2. Review the output. Is it accurate?

Reflect: If your functions lack docstrings, the generated docs will be nearly empty. This is the strongest motivation for writing good docstrings — they become your documentation automatically.

Expected outcome: You’ve seen auto-generated API docs and understand the direct connection between docstrings and documentation quality.

Exercise: Document Your Package#

  1. Add docstrings to all public functions (AI assists)

  2. Create a comprehensive README

  3. Add usage examples

  4. Generate API docs with Sphinx or MkDocs

Summary#

Doc Type

Purpose

Docstrings

Function-level docs

README

First impression

API docs

Reference

Tutorials

Learning

Tips and Tricks#

  • Prompt: “Write a numpydoc docstring for [function]”: AI generates well-formatted docstrings when you specify the style (numpydoc, Google, Sphinx).

  • Document as you go, not at the end: Ask the agent to add docstrings immediately after writing a function — it is faster when the context is fresh.

  • Prompt: “Write a README for this project based on [pyproject.toml and source files]”: AI can draft a solid README from your project metadata.

  • Use examples in docstrings: “Add a doctest example to this docstring” — examples are the most useful part of documentation for readers.

  • Prompt: “Generate API documentation for all public functions in [module]”: AI can batch-generate docstrings for an entire module in one pass.

  • Build docs locally before pushing: jupyter-book build . or sphinx-build . _build — catch broken links and formatting issues early.

  • Prompt: “Write a tutorial notebook that demonstrates [feature]”: AI generates good tutorial-style content when you specify the audience.

  • Keep your README under one screen of scrolling: If it is longer, split into separate docs pages — a README should orient, not teach.

Foundational Concepts to Commit to Memory#

  • Docstrings are documentation = they are not just comments; tools like Sphinx, pdoc, and MkDocs extract them automatically to build your API reference

  • Google-style docstring sections = Summary, Args, Returns, Raises, Examples — know this order by heart

  • Type hints + docstrings = type hints tell tools and readers what types to expect; docstrings explain what things mean and how to use them; you need both

  • README is your front door = most people decide whether to use your package in under 30 seconds based on the README alone

  • README essentials = project name, one-line description, installation, quick usage example, license — anything less and users will move on

  • Sphinx vs. MkDocs = Sphinx is the traditional Python documentation tool (reStructuredText-based); MkDocs is simpler and Markdown-based; both auto-generate docs from docstrings

  • “AI drafts, human reviews” = the standard industry workflow for documentation; AI is excellent at producing first drafts of docstrings and READMEs, but only you know if they are accurate

  • No docstring = no documentation = if you skip the docstring, auto-generated docs will show an empty entry; this is the strongest practical argument for writing them

Knowing vs. Doing: Reflection#

Documentation is perhaps the clearest example of where AI agents change the economics of software development. Writing docstrings and READMEs used to be pure overhead — necessary but slow, and most people skipped it because the cost felt too high relative to the immediate benefit. Now AI can draft a complete set of docstrings for a module in seconds. The bottleneck has shifted from writing to reviewing. And reviewing requires knowledge: you need to know what a good docstring looks like, what information matters to the reader, and whether the AI’s description of your function is actually accurate.

This is a pattern you will see throughout your career. AI keeps lowering the cost of producing things — code, docs, tests, analyses — but it raises the importance of knowing enough to evaluate what was produced. If you cannot tell whether a docstring is accurate, the AI draft is worse than no docstring at all, because it gives false confidence. The more you understand about your own code and about documentation conventions, the faster you can review and approve (or fix) what AI generates. Knowledge is not just for doing the work yourself; it is for quality control.

The trap to avoid is thinking you need to master Sphinx configuration, reStructuredText syntax, and every documentation framework before you write a single docstring. You do not. Start with Google-style docstrings and a clean README. Ship that. Learn Sphinx or MkDocs when you actually need a documentation website. AI can help you set up those tools when the time comes — but only if you know enough to tell it what you want. There is always more to learn about documentation, and there is always more documentation to write. Focus on the documentation that helps someone use your code today.

Additional Resources#

  • Sphinx Documentation — The standard documentation generator for Python projects, widely used in the scientific Python ecosystem

  • MkDocs — A simpler, Markdown-based static site generator designed for project documentation

  • Jupyter Book — Build publication-quality books and documents from Jupyter notebooks and Markdown

  • numpydoc Style Guide — The NumPy docstring convention, another widely used alternative to Google style

Next Steps#

In the final module, we’ll explore advanced topics: MCP servers and custom AI tools.