
(4.5-automated-documentation)=
# 🧩 4.5 Automated Documentation

```{contents}
:depth: 3
```

## 🔰 Tutorial

In this module, you will learn how to automate documentation creation for your Python projects using **Sphinx** and **Readthedocs**. You will also explore writing docstrings, generating documentation in **Markdown**, and understanding the concept of **documentation as code**.

Learning Objectives:
1. Write documentation in Markdown
2. Explain what "documentation as code" means
3. Write a docstring for a Python function
4. Set up a Readthedocs account and publish a Readthedocs page

### Writing Documentation in Markdown

Markdown is a lightweight markup language that uses plain text formatting to create formatted documents. It is widely used for writing documentation because of its simplicity and ease of use.

#### Why Markdown?
- **Simplicity**: Markdown files are easy to read and write without the need for complex syntax.
- **Compatibility**: Markdown is supported by many platforms (e.g., GitHub, Readthedocs).
- **Efficiency**: Markdown allows you to focus on content without worrying about formatting.

#### Basic Markdown Syntax:
- **Headings**: Use `#` for headings.
- **Lists**: Use `-` for unordered lists or `1.` for ordered lists.
- **Code blocks**: Enclose code in triple backticks.
- **Links**: Create links with `[Link text](URL)`.

#### Example Markdown Document:
```markdown
# Project Title

## Description
This is a brief description of the project.

## Installation
To install the project, run the following command:
```bash
pip install -r requirements.txt
```


## Usage
Run the following command to start the application:
```bash
python main.py
```

[More about Markdown](https://www.markdownguide.org)


Video Tutorial: [How to Write Markdown](https://www.youtube.com/watch?v=HUBNt18RFbo)

### What Documentation as Code Means

Documentation as code is a practice where documentation is written, version-controlled, and maintained in the same way as code. This approach encourages continuous updates, collaboration, and automation of the documentation process.

#### Key Points:
- Version Control: Documentation can be versioned along with code in Git.
- Automation: Tools like **Sphinx** and **Readthedocs** can automatically generate documentation from the code.
- Consistency: Since the documentation is written close to the code, it is easier to keep both in sync.

By treating documentation like code, it becomes part of the development workflow, allowing it to evolve as the project grows.

Video Tutorial: [Documentation as Code Explained](https://www.youtube.com/watch?v=XU5xt1kBuyI&pp=ygUfRG9jdW1lbnRhdGlvbiBhcyBDb2RlIEV4cGxhaW5lZA%3D%3D)

### Writing Python Docstrings

Docstrings are comments within Python functions, classes, or modules that describe their behavior. Tools like **Sphinx** can extract these docstrings and generate API documentation from them.

#### Example of a Function Docstring:
```python
def multiply(a: int, b: int) -> int:
    """
    Multiplies two numbers and returns the result.

    Parameters:
    a (int): The first number.
    b (int): The second number.

    Returns:
    int: The result of multiplying a and b.
    """
    return a * b
```

#### Steps for Writing Good Docstrings:
1. Start with a summary: Begin with a one-line summary of the function.
2. Parameters section: Describe each argument, including its type and purpose.
3. Returns section: Indicate what the function returns, including the type and expected value.

### More Docstring Examples

#### Example for a class:
```python
class Calculator:
    """
    A simple calculator class that supports addition and subtraction.
    """

    def add(self, a: int, b: int) -> int:
        """
        Adds two numbers.

        Parameters:
        a (int): The first number.
        b (int): The second number.

        Returns:
        int: The sum of the two numbers.
        """
        return a + b
```

Video Tutorial: [Writing Python Docstrings](https://www.youtube.com/watch?v=QZhANCk5OXc&pp=ygUZV3JpdGluZyBQeXRob24gRG9jc3RyaW5ncw%3D%3D)

### Setting Up Sphinx for Automated Documentation

Sphinx is a documentation generator that converts reStructuredText or Markdown files into various output formats (HTML, PDF, etc.). It can extract Python docstrings to create clean, organized API documentation.

#### Steps to Set Up Sphinx:

1. Install Sphinx:
   ```bash
   pip install sphinx
   ```
2. Initialize Sphinx Project:
   Run `sphinx-quickstart` in your project folder and follow the prompts to set up the basic structure:
   ```bash
   sphinx-quickstart
   ```
   This will generate the necessary configuration files.

3. Configure Sphinx:
   - Modify the `conf.py` file to include the source directory where your Python files are located.
   - Example modification:
     ```python
     import os
     import sys

     sys.path.insert(0, os.path.abspath("../src"))
     ```

4. Add Extensions:
   To use Markdown files or automate docstring extraction, add extensions in `conf.py`:
   ```python
   extensions = ["sphinx.ext.autodoc", "myst_parser"]
   ```

5. Build the Documentation:
   After making changes, run:
   ```bash
   make html
   ```
   This command will generate HTML documentation in the `_build/html/` directory.

Video Tutorial: [Sphinx Documentation Setup](https://www.youtube.com/watch?v=BWIrhgCAae0&pp=ygUaU3BoaW54IERvY3VtZW50YXRpb24gU2V0dXA%3D)

### Publishing Documentation with Readthedocs

Readthedocs is a popular platform for hosting and automatically building documentation from your repository. It integrates seamlessly with Sphinx and GitHub.

#### Steps to Set Up and Publish on Readthedocs:
1. Create an Account: Go to [Readthedocs](https://readthedocs.org/) and sign up for an account.
2. Connect Your Repository: After signing in, connect your GitHub repository with Readthedocs.
3. Add a `docs/` folder:
   Ensure that your project contains a `docs/` folder with the Sphinx configuration files (`conf.py`, `index.rst` or `index.md`).

4. Set Up Readthedocs:
   - In your Readthedocs dashboard, import the project by selecting your GitHub repository.
   - Follow the prompts to configure your build settings (e.g., Python version, Sphinx builder).

5. Build the Documentation:
   - Click "Build" in Readthedocs to generate the documentation.
   - Once the build is complete, your documentation will be available at a public URL.

Video Tutorial: [Host your documentation on ReadTheDocs](https://www.youtube.com/watch?v=PO4Zd-6a6fA&pp=ygULUmVhZHRoZWRvY3M%3D)

### Additional Resources

- [Sphinx Documentation](https://www.sphinx-doc.org/en/master/)
- [Readthedocs Documentation](https://docs.readthedocs.io/en/stable/)
- [Markdown Guide](https://www.markdownguide.org/)

## 🚀 Quiz

::::{tab-set}
:sync-group: category

:::{tab-item} W 2024
:sync: w2024

:::

:::{tab-item} Sp/Su 2024
:sync: sp2024

https://q.utoronto.ca/courses/370070/assignments/1393627?display=full_width
:::

:::{tab-item} Sp/Su 2025
:sync: sp2025

https://q.utoronto.ca/courses/393352/assignments/1499729?display=full_width_with_nav
:::

::::

## 📄 Assignment

::::{tab-set}
:sync-group: category

:::{tab-item} W 2024
:sync: w2024

:::

:::{tab-item} Sp/Su 2024
:sync: sp2024

https://q.utoronto.ca/courses/370070/assignments/1394233?display=full_width
:::

:::{tab-item} Sp/Su 2025
:sync: sp2025

https://q.utoronto.ca/courses/393352/assignments/1499730?display=full_width_with_nav
:::

::::
