# Python Documentation Standards (UIA)

Documentation architecture and writing standards for Python OSS projects, based on the Diátaxis framework with MkDocs Material + mkdocstrings.

<rules>
- **FRAMEWORK:** Structure all documentation using the 4 Diátaxis quadrants — Tutorials, How-To Guides, Reference, Explanation.
- **PURITY:** Never mix quadrant types within a single page. Blurring boundaries is the root cause of most documentation failures.
- **TONE:** Match tone to quadrant — instructional for tutorials, directive for how-to, terse for reference, narrative for explanation.
- **DOCSTRINGS:** Google-style exclusively; omit types in docstring (pulled from signatures by mkdocstrings).
- **CASE:** Sentence case for all page titles and headings (only first word and proper nouns capitalized).
- **EMOJI:** Allowed in nav titles, H2–H6 section headings, and admonition titles. Never in prose sentences, docstrings, or code comments.
- **CLI:** Treat CLI as a Reference sub-section (`cli/`). One page per command group for large CLIs.
- **EXAMPLES:** `examples/` is a standalone section, not Diátaxis. Each example is one H2, self-contained, copy-paste ready.
- **BADGES:** Place on `docs/index.md` only, on a single line after H1, using shields.io `flat` style.
</rules>

## The 4 Diátaxis Quadrants

| Quadrant        | User state          | Answers                        | Form        |
| :-------------- | :------------------ | :----------------------------- | :---------- |
| **Tutorial**    | Learning, beginner  | "Help me acquire this skill"   | Lesson      |
| **How-To**      | Working, competent  | "Help me accomplish this task" | Recipe      |
| **Reference**   | Working, looking up | "What does this do exactly?"   | Description |
| **Explanation** | Studying, curious   | "Why does it work this way?"   | Discussion  |

## Navigation Structure

```
docs/
├── index.md                   ← project overview, badges, quick install, links to all sections
├── getting-started.md         ← Tutorial: install + first run
├── guides/                    ← How-To (task-oriented recipes)
│   ├── index.md               ← navigation index listing all guides
│   ├── how-to-configure-x.md
│   └── development.md
├── api/                       ← Reference (auto-generated)
│   ├── index.md               ← curated navigation index listing modules/classes
│   └── reference/
│       └── index.md           ← ::: my_project (full mkdocstrings dump)
├── cli/                       ← Reference sub-section for CLI tools
│   └── index.md               ← command/option tables (static Reference page)
├── examples/                  ← runnable end-to-end code examples
│   └── index.md               ← self-contained snippets, one section per scenario
├── concepts/                  ← Explanation (understanding-oriented)
│   ├── index.md
│   └── about-architecture.md
├── architecture.md            ← auto-generated by generate_architecture_graph.py
├── coverage.md                ← auto-generated by pytest-cov
└── changelog.md               ← auto-generated by git-cliff
```

### `api/index.md` vs `api/reference/index.md`

| File                     | Purpose                                                          |
| :----------------------- | :--------------------------------------------------------------- |
| `api/index.md`           | Human-curated navigation index — one row per public module/class |
| `api/reference/index.md` | Full mkdocstrings auto-dump — all symbols, generated from source |

Use `api/index.md` as the landing page for the API section (linked from `docs/index.md`).
The `reference/` sub-page is the authoritative exhaustive listing.

Nav label aliases — pick one set, be consistent:

| Quadrant    | Primary       | Acceptable aliases           |
| :---------- | :------------ | :--------------------------- |
| Tutorial    | Tutorials     | Getting Started, Quickstart  |
| How-To      | Guides        | How-To, Recipes              |
| Reference   | API Reference | Reference, API               |
| Reference   | CLI Reference | CLI, Commands                |
| —           | Examples      | Cookbook, Snippets           |
| Explanation | Concepts      | Understanding, Topics, About |

## Page Structure by Quadrant

### Tutorial

Goal: guide a beginner to a working outcome. Never presume, never digress.

```markdown
# [Outcome-focused title, e.g. "Build your first pipeline"]

Brief context — what the learner will have accomplished by the end.

## Prerequisites

- Bullet list of required knowledge and tools (link to install guides)

## Step 1 — [Action]

Short imperative sentence. One action per step.
Verify success: "You should see..."

## Step 2 — [Action]

...

## What you built

Two-sentence recap of what was accomplished.

## Next steps

- [How to configure X](../guides/how-to-configure-x.md)
- [Reference: MyClass](../api/reference/index.md#myclass)
```

Rules: numbered steps, imperative mood, minimal "why", include success checks, end with pointers to How-To / Reference.

---

### How-To Guide

Goal: help a competent user accomplish a specific real-world task.

````markdown
# How to [accomplish specific goal]

One sentence stating what problem this solves.

## Prerequisites

- What the user must already have or know

## Steps

1. First action.
2. Second action.
   ```python
   # concrete example
   ```
````

3. Third action.

## Variations

If condition X applies, replace step 2 with...

## Result

What success looks like.

````

Rules: goal-oriented title (imperative verb), no theory, accommodate user context with conditional variations.

---

### Reference
Goal: accurate, complete, fast-lookup technical description.

```markdown
# [Class / Module / Config key name]

One-line description of what it is (not what it does for the user).

::: my_project.module.ClassName
    options:
      show_source: true
      members_order: source
````

Rules: terse, no instructions, no "chatty" prose. Auto-generate from Google-style docstrings via mkdocstrings. Structure mirrors code architecture.

---

### Explanation

Goal: build understanding of the "why" behind design choices.

```markdown
# [Concept name / "About [topic]"]

High-level overview of the topic and why it matters.

## Background

Context that makes the design understandable.

## Design reasoning

Why it was built this way; alternatives considered and trade-offs.

## Relationship to [other concept]

How this connects to other parts of the system.
```

Rules: narrative tone, no step-by-step instructions, explore trade-offs, weave connections to other concepts.

### CLI Reference

Goal: static, fast-lookup reference for every command, sub-command, option, and flag.

````markdown
# CLI reference

One-line description of the top-level command.

## 💻 Usage

```bash
my-project [OPTIONS] COMMAND [ARGS]...
```
````

## ⚙️ Global options

| Option      | Short | Description               |
| :---------- | :---- | :------------------------ |
| `--version` |       | Show the version and exit |
| `--help`    | `-h`  | Show help and exit        |

## 📋 Commands

| Command        | Description                      |
| :------------- | :------------------------------- |
| `command-name` | _Replace with your CLI commands_ |

## 🧪 Examples

```bash
# Show version
my-project --version

# Run a command
my-project command-name --option value
```

````

Rules: Reference quadrant — no narrative, no theory. One page per command group if the
CLI is large. Use sub-pages `cli/command-name.md` for complex sub-commands.

---

### Examples

Goal: self-contained, runnable code snippets for common scenarios. Not a tutorial
(no step-by-step learning arc) and not a How-To (no prerequisites, no variations).

```markdown
# Examples

Brief sentence stating what readers will find here.

## 🚀 Basic usage

```python
from my_project import MyClass

instance = MyClass()
print(instance.run())
````

## 💡 Example title — _replace with scenario name_

```python
from my_project import MyClass

instance = MyClass(option="value")
print(instance.run())
```

!!! tip
All examples assume the package is installed: `pip install my-project`

````

Rules: each example is one H2 section, self-contained, with a copy-paste code block.
No prose between examples. Keep scenarios distinct — do not duplicate the tutorial.

---

## `docs/index.md` — project homepage

The homepage combines elements from all quadrants but belongs to none. Its role is
orientation and quick-start, not deep instruction.

### Required sections

```markdown
# Project name

[badges line]

**project-name** — one-sentence description.

## 🚀 Quick start

Install snippet + minimal usage snippet (< 10 lines total).

## ✨ Key features

- Bullet list (3–5 items max)

## 📚 Documentation

Navigation table — one row per section with a one-line description.

## 📋 Requirements

- Python >= x.y

## ⚖️ License

One-line reference to the LICENSE file.
````

### Badges

Place badges on a single line immediately after the H1, before any prose.
Use [shields.io](https://shields.io/) `flat` style with logo. Standard badge set:

```markdown
[![PyPI version](https://img.shields.io/pypi/v/{{my-project}}?style=flat&logo=pypi&logoColor=white)](https://pypi.org/project/{{my-project}}/)
[![Python versions](https://img.shields.io/pypi/pyversions/{{my-project}}?style=flat&logo=python&logoColor=white)](https://pypi.org/project/{{my-project}}/)
[![PyPI status](https://img.shields.io/pypi/status/{{my-project}}?style=flat&logo=pypi&logoColor=white)](https://pypi.org/project/{{my-project}}/)
[![License](https://img.shields.io/badge/license-MIT-green?style=flat&logo=github&logoColor=white)](https://github.com/{{github-owner}}/{{my-project}}/blob/main/LICENSE)
[![CI](https://img.shields.io/github/actions/workflow/status/{{github-owner}}/{{my-project}}/publish-pypi.yml?style=flat&label=publish&logo=githubactions&logoColor=white)](https://github.com/{{github-owner}}/{{my-project}}/actions/workflows/publish-pypi.yml)
[![Docs](https://img.shields.io/badge/docs-Github%20Pages-blue?style=flat&logo=materialformkdocs&logoColor=white)](https://{{github-owner}}.github.io/{{my-project}}/)
[![uv](https://img.shields.io/badge/package%20manager-uv-DE5FE9?style=flat&logo=uv&logoColor=white)](https://github.com/astral-sh/uv)
[![linter](https://img.shields.io/badge/linter-ruff-orange?style=flat&logo=ruff&logoColor=white)](https://github.com/astral-sh/ruff)
[![type checker](https://img.shields.io/badge/type%20checker-ty-orange?style=flat&logo=astral&logoColor=white)](https://github.com/astral-sh/ty)
```

Badge rules:

- Badges are prose content — no emoji in the badge line itself.
- Always use `flat` style for visual consistency.
- Add or remove badges based on what the project actually uses.

---

## Google-Style Docstrings (mkdocstrings)

Omit types in docstring body — mkdocstrings pulls them from the function signature.

```python
def process(data: list[float], threshold: float = 0.5) -> dict[str, float]:
    """Filters and aggregates measurement data.

    Args:
        data: Raw measurements to process.
        threshold: Values below this are discarded.

    Returns:
        Mapping of metric names to aggregated values.

    Raises:
        ValueError: If `data` is empty.

    Example:
        >>> process([0.1, 0.9, 0.4], threshold=0.3)
        {'mean': 0.65, 'count': 2}
    """
```

Recognized section headers (case-insensitive): `Args`, `Returns`, `Raises`, `Example`, `Note`, `Warning`, `Tip`, `See also`.
`Note:` / `Warning:` / `Tip:` sections render as MkDocs Material admonitions automatically.

## Admonitions (MkDocs Material)

Use admonitions to signal meta-information without polluting prose.

```markdown
!!! tip "Performance"
Use `uv sync --frozen` in CI to avoid re-solving the lockfile.

!!! warning
This method mutates the input list in place.

??? note "Implementation detail"
Collapsible — use for information that is true but not critical to the flow.
```

| Type       | Use for                                          |
| :--------- | :----------------------------------------------- |
| `note`     | Neutral supplementary information                |
| `tip`      | Shortcuts, better ways, non-obvious improvements |
| `warning`  | Behaviour that surprises or causes data loss     |
| `danger`   | Security or irreversible actions                 |
| `example`  | Standalone runnable code blocks                  |
| `abstract` | Summaries at the top of long explanation pages   |

## Emoji Usage

Emojis are permitted in **nav titles**, **section headings (H2–H6)**, and **admonition titles**.
They are **never** permitted in prose sentences, docstrings, or code comments.

```yaml
# mkdocs.yml nav — OK
nav:
  - 🚀 Getting Started: getting-started.md
  - 📖 Guides: guides/index.md
  - 🔧 API Reference: api/index.md
  - 💻 CLI Reference: cli/index.md
  - 💡 Examples: examples/index.md
  - 🧠 Concepts: concepts/index.md
```

```markdown
<!-- Section headings — OK -->

## 🚀 Quick start

## 🔧 Prerequisites

## 📝 Steps

## ✅ Result

## ➡️ Next steps

<!-- Admonition title — OK -->

!!! tip "🚀 Quick path"
Run `uv sync` to get started in one step.

<!-- Prose sentence — NOT OK -->

🚀 Install the package and you're ready to go. ← avoid
```

### Standard emoji set for section headings

| Section type       | Emoji | Usage                                     |
| :----------------- | :---- | :---------------------------------------- |
| Quick start        | 🚀    | Installation + minimal usage on homepage  |
| Key features       | ✨    | Feature list on homepage                  |
| Documentation nav  | 📚    | Navigation table on homepage              |
| Requirements       | 📋    | Dependency / Python version list          |
| License            | ⚖️    | License reference                         |
| Prerequisites      | 🔧    | Required knowledge and tools              |
| Steps              | 📝    | Numbered steps in How-To / Tutorial       |
| Result / outcome   | ✅    | Success state at end of guide or tutorial |
| Next steps         | ➡️    | Links to related pages                    |
| CLI usage          | 💻    | Command syntax block                      |
| CLI options        | ⚙️    | Option/flag tables                        |
| CLI commands       | 📋    | Command listing tables                    |
| CLI examples       | 🧪    | Short CLI invocation snippets             |
| Code examples      | 🚀    | First / basic example block               |
| Additional example | 💡    | Second and subsequent example blocks      |
| Test suite         | 🧪    | Running tests section                     |
| Coverage           | 📊    | Coverage reporting section                |
| New test           | ✏️    | Writing tests section                     |
| Modules (API)      | 📦    | Module listing table in `api/index.md`    |
| Full reference     | 🔍    | Link to mkdocstrings auto-dump            |

## Naming Conventions

| Pattern           | Example                                                 |
| :---------------- | :------------------------------------------------------ |
| Tutorial files    | `getting-started.md`, `build-first-pipeline.md`         |
| How-To files      | `how-to-configure-logging.md`                           |
| Explanation files | `about-architecture.md`, `understanding-concurrency.md` |
| Reference files   | mirror module path — `api/reference/client.md`          |
| All headings      | Sentence case only                                      |

## Anti-Patterns

| Anti-pattern                               | Problem                                 | Fix                                                       |
| :----------------------------------------- | :-------------------------------------- | :-------------------------------------------------------- |
| Tutorial that explains "why" at each step  | Cognitive overload, loses learning flow | Move theory to Explanation page                           |
| How-To guide that teaches from scratch     | Conflates learning with doing           | Split: Tutorial for beginners, How-To for competent users |
| Reference with "chatty" prose              | Slows down lookup                       | Trim to facts; link to Explanation for context            |
| Explanation with step-by-step instructions | Wrong quadrant                          | Move steps to How-To                                      |
| One mega-page covering all four types      | Navigation impossible                   | Decompose into separate pages                             |
| Creating empty skeleton structure upfront  | Structure without content adds no value | Apply Diátaxis bottom-up to real pages                    |

<examples>
<!-- Good How-To title -->
# How to configure structured JSON logging

<!-- Bad — mixes intent, unclear quadrant -->

# Logging in my_project

<!-- Good Reference entry — terse -->

# StreamProcessor

Consumes an event stream and applies registered transforms in order.

::: my_project.processing.StreamProcessor

<!-- Bad Reference — instructional prose in reference -->

# StreamProcessor

Use this class when you need to process events. First, instantiate it, then...
</examples>

<success_criteria>

- Every doc page belongs unambiguously to exactly one Diátaxis quadrant (or to the special `examples/` section).
- Tutorials end with a working outcome and pointers to How-To / Reference.
- Reference pages are generated from Google-style docstrings via mkdocstrings.
- `api/index.md` is a human-curated navigation index; `api/reference/index.md` is the full mkdocstrings dump.
- `cli/` contains static Reference pages — no instructions, no narrative.
- `examples/` contains self-contained snippets; each example is one H2 section.
- `docs/index.md` carries the badges block, a quick-start snippet, and the navigation table.
- Emojis appear in nav titles, H2–H6 headings, and admonition titles only — never in prose.
- All headings in sentence case.
- No step-by-step instructions appear in Explanation pages.
- No theory or "why" blocks appear inside How-To steps.

</success_criteria>
