Python > Quality and Best Practices > Documentation > Using Read the Docs

Setting up Read the Docs for Your Python Project

This snippet demonstrates how to structure your Python project to integrate seamlessly with Read the Docs (RTD) for automated documentation builds. We'll cover creating a `docs` directory, setting up a `conf.py` file, and structuring your Python code for Sphinx to generate documentation.

Project Structure

Before diving into the code, it's essential to understand the recommended project structure for Read the Docs. Typically, you'll have a root directory containing your Python package's code, a `docs` directory for documentation-related files, and a `setup.py` file for packaging. For example: my_project/ ├── my_package/ │ ├── __init__.py │ ├── module1.py │ └── module2.py ├── docs/ │ ├── conf.py │ ├── index.rst │ └── ... ├── setup.py ├── README.md └── LICENSE

Creating the `docs` Directory

The `docs` directory will house all your documentation files. Create a directory named `docs` in your project's root directory. This is where you'll configure Sphinx.

Generating `conf.py` with `sphinx-quickstart`

The easiest way to get started is using the `sphinx-quickstart` tool. Navigate to your project's root directory in your terminal and run `sphinx-quickstart docs`. This interactive tool will guide you through creating a basic `conf.py` file. Answer the prompts appropriately, making sure to set up autodoc. Here's a typical configuration: * **Separate source and build directories (y/n) [n]:** y * **Project name:** My Project * **Author name(s):** Your Name * **Project release:** 1.0 * **Source file suffix [.rst]:** .rst * **Name for your master document (without suffix) [index]:** index * **Project language [en]:** en * **Create Makefile? (y/n) [y]:** y * **Create Windows command file? (y/n) [y]:** y * **Create batch file? (y/n) [n]:** n * **Create link to the sphinx-quickstart man page? (y/n) [n]:** n * **Create a sample conf.py file with advanced options? (y/n) [n]:** n * **Create .gitignore file? (y/n) [.gitignore]:** .gitignore * **Autodoc extension: automatically insert docstrings from modules (y/n) [n]:** y * **Doctest extension: automatically test code snippets in doctest blocks (y/n) [n]:** n * **Coverage extension: track coverage of doctest blocks (y/n) [n]:** n * **MathJax extension: include math, rendered in browser by MathJax (y/n) [n]:** n * **graphviz extension: include images from Graphviz (y/n) [n]:** n * **InterSphinx extension: link to the documentation of other Sphinx projects (y/n) [n]:** n * **Create todo files? (y/n) [n]:** n * **nitpicky mode: warn about all missing references (y/n) [n]:** n

sphinx-quickstart docs

Configuring `conf.py` for Autodoc

The `conf.py` file contains the configuration for your Sphinx documentation. You need to configure it so Sphinx can find your Python modules and generate documentation from docstrings. Here are the key configurations to adjust: 1. **`sys.path`**: Add your project's root directory to the Python path. This allows Sphinx to find your modules. Add the following lines to the top of your `conf.py` file: python import os import sys sys.path.insert(0, os.path.abspath('..')) 2. **`extensions`**: Make sure the `sphinx.ext.autodoc` extension is enabled. In the `extensions` list, ensure you have `'sphinx.ext.autodoc'`. 3. **`html_theme`**: Choose a theme for your documentation, such as `'sphinx_rtd_theme'`. This theme is popular with Read the Docs. You may need to install it using pip: `pip install sphinx_rtd_theme`. Then, in `conf.py`: python html_theme = 'sphinx_rtd_theme'

Example `conf.py`

This is a sample `conf.py` file demonstrating the necessary configurations for autodoc and the Read the Docs theme.

import os
import sys
sys.path.insert(0, os.path.abspath('..'))

# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -------------------------------------------------------

project = 'My Project'
copyright = '2023, Your Name'
author = 'Your Name'
release = '1.0'

# -- General configuration -----------------------------------------------------

extensions = [
    'sphinx.ext.autodoc',
    'sphinx_rtd_theme'
]

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']



# -- Options for HTML output -------------------------------------------------

html_theme = 'sphinx_rtd_theme'

Documenting Your Code with Docstrings

Sphinx uses docstrings to generate documentation. Write clear and comprehensive docstrings for your functions, classes, and modules. The example above uses the reStructuredText (reST) format, which is the standard for Sphinx. Use the `:param`, `:type`, `:raises`, `:returns`, and `:rtype` directives to describe your function's parameters, types, exceptions, return values, and return types. Include examples to showcase how to use your code.

def add(x, y):
    """Adds two numbers together.

    :param x: The first number.
    :type x: int or float
    :param y: The second number.
    :type y: int or float
    :raises TypeError: If x or y is not a number.
    :returns: The sum of x and y.
    :rtype: int or float

    :Example:

    >>> add(1, 2)
    3
    """
    if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
        raise TypeError("Inputs must be numbers")
    return x + y

Creating an `index.rst` File

The `index.rst` file is the main page of your documentation. It contains the table of contents and links to other pages. To automatically generate documentation for your modules, you need to use the `automodule` directive. Here's how to structure your `index.rst`: 1. **Table of Contents:** Use the `toctree` directive to create the table of contents. Specify the modules you want to include. 2. **Module Documentation:** Create separate `.rst` files for each module (e.g., `module1.rst`, `module2.rst`). In each module file, use the `automodule` directive to generate documentation from the module's docstrings. Here is an example `module1.rst` file: rest module1 ======= .. automodule:: my_package.module1 :members: This will generate documentation for the `my_package.module1` module, including all its members (functions, classes, etc.).

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   module1
   module2

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Generating Documentation Locally

To build the documentation locally, navigate to your `docs` directory in your terminal and run `make html`. This will generate the documentation in the `docs/_build/html` directory. Open `docs/_build/html/index.html` in your browser to view the documentation.

make html

Configuring Read the Docs

1. **Create an account on Read the Docs:** Go to [https://readthedocs.org/](https://readthedocs.org/) and sign up for an account. 2. **Import your repository:** Connect your Read the Docs account to your code repository (e.g., GitHub, GitLab, Bitbucket). Import your project's repository. 3. **Configure your project:** Read the Docs will automatically detect your project and build the documentation. You might need to specify the location of your `conf.py` file and the Python version to use. 4. **Set up a `.readthedocs.yaml` file (optional, but recommended):** This file provides more control over the build process. Place this file in the root of your repository. A minimal example: yaml version: 2 formats: all python: version: 3.7 install: - requirements: docs/requirements.txt Create a `docs/requirements.txt` file and add the libraries required to build your documentation, e.g., `sphinx`, `sphinx-rtd-theme`.

Real-Life Use Case

Consider a library for data analysis. Using Read the Docs, you can automatically generate API documentation from the library's docstrings, making it easy for users to understand and use the library's functions and classes. This allows users to quickly reference parameter types, return values, and examples without having to dive into the source code.

Best Practices

  • Write Clear Docstrings: Follow a consistent style (e.g., reStructuredText) and provide detailed explanations of your code.
  • Keep Documentation Up-to-Date: Update your documentation whenever you make changes to your code.
  • Use Examples: Provide practical examples of how to use your code in your docstrings.
  • Version Your Documentation: Use tags or branches in your repository to version your documentation, ensuring users can access the documentation that matches their version of the code.

When to Use Read the Docs

Use Read the Docs when you want to automatically generate and host documentation for your Python project. It's especially useful for open-source projects, libraries, and APIs that need to be easily accessible to users.

Pros

  • Automated Builds: Read the Docs automatically builds documentation whenever you push changes to your repository.
  • Version Control Integration: Seamlessly integrates with popular version control systems like GitHub, GitLab, and Bitbucket.
  • Free Hosting: Provides free hosting for your documentation.
  • Customization: Offers various customization options for your documentation's appearance and behavior.

Cons

  • Learning Curve: Requires some initial setup and understanding of Sphinx and reStructuredText.
  • Limited Control: Compared to self-hosting your documentation, you have less control over the server environment.

FAQ

  • Why is my documentation not building on Read the Docs?

    Check your `.readthedocs.yaml` file, `conf.py` file, and dependencies. Ensure that Read the Docs can find your `conf.py` file and that all required dependencies are installed in your `docs/requirements.txt` file. Also, review the Read the Docs build logs for any error messages.
  • How do I add documentation for a specific module or class?

    Create a separate `.rst` file for the module or class and use the `automodule` or `autoclass` directives in the file. Then, link to the file from your `index.rst` file using the `toctree` directive.
  • Can I use a different documentation generator with Read the Docs?

    Read the Docs primarily supports Sphinx, but you can configure it to use other documentation generators by providing custom build commands in your `.readthedocs.yaml` file. However, this may require more advanced configuration.