Write and Publish Python Code Documentation Automatically
Tags: python, docstring, tutorial, programming
Published: 2022-07-11 09:10:31

We all know that programmers write code but many of us are not aware that they read more than write. The clean code will be easier to read. In this article, I am going to explain about the process of writing and publishing the python code documentation easy and effective way. Below is the table of content,

[1. Write the standard docstring](#1)
[2. Install Sphinx](#2)
[3. Initialize Sphinx](#3)
[4. Update the `conf.py` file](#4)
[5. Auto generate the `rst` file](#5)
[6. Build HTML](#6)
[7. Publish the documentation online](#7)
[8. Reference](#8)

## <a name='1'></a> 1. Write the standard docstring

Good programmers prefer to write the logic behind each class, methods, function etc using comments. In python, the best way to add the comments for the functions or class is to write in docstring format. Later, it can be used by documentation automation tools like [sphnix](https://www.sphinx-doc.org/en/master/) to generate the document. But for the automation, you should follow the [standard docstring guideline](https://realpython.com/documenting-python-code/). Here is the small example of good docstring example,

```python
def add(x, y):
    """Function to add two numbers 

        Parameters
        ----------
        x: int
            First number to add
        y: int
            Second number to add

        Returns
        -------
        int
            The sum of x and y
        """
    return x + y
```

## <a name='2'></a> 2. Install sphinx

Now next step is to install the sphnix. It can be installed easily using `pip` command,

```shell
pip install sphinx
```

## <a name='3'></a> 3. Initialize the sphinx
In the root directory of your project, run `sphinx-quickstart` to initialize the sphinx source directory to create a default configuration. I prefer to have separated directory for `build` and `source`, I hope you will also do the same.

```shell
sphinx-quickstart
```

Below image is the example of my `sphinx-quickstart`,

![sphinx-quickstart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhgp0ammkqnzdg2drm80.png)

As shown above, running the sphinx-build command creates a `Makefile`, a `make.bat` file, as well as `build` and `source` directories.

## <a name='4'></a> 4. Update the `conf.py` file

The `conf.py` file is inside the `source` folder which describes the sphinx configurations to control the documentation. Here, I recommend you to overwrite the following things,

### Add project information

In the project information section, you need to update about `copyright`, `author`, `release` etc. Following is the example of my project information,

```python
# -- Project information -----------------------------------------------------

project = 'GeoTile'
copyright = '2022, Tek Kshetri'
author = 'Tek Kshetri'

# The full version, including alpha/beta/rc tags
release = '0.1.0'
```

### Add extensions

By default, there will be no extension added to the documentation. You have to add at least following extension to generate the documentation

```python
extensions = [
   'sphinx.ext.doctest',
   'sphinx.ext.autodoc',
   'sphinx.ext.autosummary',
   'sphinx.ext.napoleon',
]
```

### Update theme

The default theme for sphinx is [alabaster](https://alabaster.readthedocs.io/en/latest/). There are several other themes are available, but personally, I like `pydata_sphinx_theme`. To change the theme, you need to install it first using terminal,

```shell
pip install pydata_sphinx_theme
```

And update it to the `conf.py` file,

```python
# html theme for documentation
html_theme = "pydata_sphinx_theme"
```

There are several ways to customize this theme. If you are interested, please check the [official documentation of `pydata_sphinx_theme`](https://pydata-sphinx-theme.readthedocs.io/en/latest/)

### Specify the location of the python modules

At the top of the `conf.py` file, you will see some commented line of code. If your python code path is outside the documentation directory (Most of the case is like this), you have to specify the path to the code like below,

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

Here is my folder structure,

![Folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9n466ku9kl7z20o5u6cu.png)

## <a name='5'></a> 5. Auto generate the `rst` file

Sphinx generates the HTML documentation from reStructuredText (rst) files. To autogenerate the rst files, run the sphinx-apidoc command using following syntax:

```shell
sphinx-apidoc -o <OUTPUT_PATH> <MODULE_PATH>
```

In my case, the output directory is `source`, and the module directory is `testCode`. I have to run following command from documentation root folder,

```shell
sphinx-apidoc -f -o source ../testCode
```

The above command will create at least two files, `modules.rst` and `test.rst`. You can open it with any text editor and see the configuration or manually edit the things as well. 

## <a name='6'></a> 6. Build HTML

Before building the HTML document, we need to insert the `modules.rst` file to `source/index.rst` file `toctree`. Please add the `API reference <modules>` to `toctree` as below,

```rst
.. toctree::
   :maxdepth: 2
   :caption: Test Documentation

   API reference <modules>
```

After that run the following command from your documentation root directory,

```shell
make html
```

This command will generate the `html` file inside the `build` directory. You can open it with any browser to check the documentation. 

## <a name='7'></a> 7. Publish the documentation online

To publish the documentation, I am going to use [Read the Docs](https://readthedocs.org/) open-source solution. Using `read the docs`, you can publish your documentation free of cost. Here is the guideline for publishing,

### Create account 
If you don't have `read the docs` account, [create account](https://readthedocs.org/accounts/signup/) and login to the read the docs site. 

### Import project

In your user dashboard, there is option to **Import a Project**. Click the option, again click on **Import Manually** button. Add the project name, repository URL (GitHub url to your documentation), and default branch and click next.

![Project details(read the docs)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/367ceofyr3c2pji4hsr4.png)

Again add the extra details about your project.

![extra details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxq32rh1ob10ofqmwx5q.png)
 
The final step is to build the version and view the docs,

![Read the docs build](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0abqnuyte59m0c6lqyp7.png)

If you did everything correctly, live version of your documentation will be rendered after clicking view docs button.

I hope this blog post is informative for you. If you like this blog, please support me by subscribing to my YouTube channel: https://www.youtube.com/c/iamtekson

# <a name='8'></a> 8. Reference
1. [Documenting python code (Blog post)](https://realpython.com/documenting-python-code/)
2. [Automatic documentation generation from code (official documentation)](https://www.sphinx-doc.org/en/master/tutorial/automatic-doc-generation.html)
3. [RST documentation guidline](https://docutils.sourceforge.io/rst.html)