Better docstrings#

Good Python code should have docstrings. This allows a user or developer to understand how to use a function and what it indends to do. Your code may already have docstrings, but you may need to modify them to allow automatic documentation generation. This will save you a lot of time as opposed to manually writing an API.

If you use Numpy- or Google-style docstrings, you can use the napoleon extension to automatically convert them to reStructuredText. Add the napoleon extension to your Sphinx configuration file docs/conf.py.

conf.py#
extensions = [
    ...,
    'sphinx.ext.napoleon',
]

Sphinx will then convert the docstrings to reStructuredText during the build.

Using our example from before, we write the docstrings in the Google style:

letters.py#
import random


class Letters:
    """Class for letters.

    Args:
        s (str): The letters to use.

    Example:
        A short usage example.

        >>> letters = Letters('abc')
        >>> print(letters)
        'abc'
    """
    def __init__(self, s: str):
        if not s.isalpha():
            raise ValueError("String must be only letters.")
        self._s = s

    def __repr__(self):
        return f"Letters({self._s})"

    def __str__(self):
        return self._s

    def shuffle(self):
        """Randomly shuffle the letters.

        Example:
            >>> letters = Letters('abcde')
            >>> letters.shuffle()
            >>> print(letters)
            'cabed'
        """
        self._s = ''.join(random.sample(self._s, len(self._s)))

    def get_random_letter(self):
        """Return a random letter.

        Returns:
            str: A random letter.
        """
        return random.choice(self._s)