Dude Engineering

View Original

Docstrings (Google-formatted)

Using docstrings is a best practice for letting other developers know what is going on in your code. By using keywords and sections in your docstrings, you can create comprehensive, structured, and readable documentation for your Python code. This makes it easier for others (and your future self) to understand and use your code effectively. Below, we’ll briefly go over how to use Google-style docstrings.

Google-Style Docstring Format

1. Short Description

A brief summary of what the function/method does. This comes right after the triple quotes.

2. Longer Description

(Optional) A more detailed description of the function or method. It can span multiple lines and is useful when a brief summary isn't enough to explain the purpose of the function.

3. Args:

List the parameters the function or method takes. For each parameter, specify its name, type, and a brief description.

Example:

Args:
    param1 (int): Description of `param1`.
    param2 (str): Description of `param2`.

4. Returns:

Describe the type and purpose of the function's return value.

Example:

Returns:
    bool: Description of the return value.

5. Raises:

(Optional) List any exceptions that the function or method is known to raise. This is especially useful for making users of your code aware of potential errors.

Example:

Raises:
    ValueError: Description of the condition under which `ValueError` is raised.

6. Yields:

(Optional) Used for generator functions to describe the type and purpose of the values yielded by the generator.

Example:

Yields:
    int: Description of the yielded value.

7. Examples:

(Optional) Provide usage examples for the function or method. This can be especially helpful for complex functions.

Example:

Examples:
    >>> function_name(1, "example")
    Expected output

8. Attributes:

(Optional) For classes, list and describe the attributes of the class.

Example:

Attributes:
    attr1 (int): Description of `attr1`.
    attr2 (str): Description of `attr2`.

9. Note:

(Optional) Include additional notes or important information about the function or method.

Example:

Note:
    Any important information or usage tips.

10. References:

(Optional) Provide references or links to related material or sources that influenced the function's design or implementation.

Example:

References:
    [1] Link or citation for a relevant source or material.

Full Example

def generate_docstring(func_name, params, return_type, raises, examples):
    """
    Generates a Google-style docstring for a given function.

    This function takes details about another function and generates a docstring that
    describes the function's purpose, its parameters, return type, exceptions it may raise,
    and provides usage examples. The generated docstring follows the conventions outlined in
    Google's Python style guide, aiming to enhance code readability and maintainability.

    Args:
        func_name (str): The name of the function for which to generate the docstring.
        params (dict): A dictionary where keys are parameter names as strings and values are
            tuples containing the parameter type as a string and a brief description.
        return_type (tuple): A tuple containing the return type as a string and a brief
            description of the return value.
        raises (dict): A dictionary where keys are exception names as strings and values are
            brief descriptions of the conditions under which the exceptions are raised.
        examples (list of str): A list of strings, each representing a usage example.

    Returns:
        str: A formatted docstring for the specified function, adhering to Google's Python
        style guide.

    Examples:
        >>> generate_docstring(
                'add',
                {'x': ('int', 'The first addend'), 'y': ('int', 'The second addend')},
                ('int', 'The sum of x and y'),
                {'ValueError': 'If either x or y is not an integer'},
                ['>>> add(2, 3)', '5']
            )
        '''
        Adds two integers.

        Args:
            x (int): The first addend.
            y (int): The second addend.

        Returns:
            int: The sum of x and y.

        Raises:
            ValueError: If either x or y is not an integer.

        Examples:
            >>> add(2, 3)
            5
        '''

    Note:
        This function is a meta example illustrating how to generate docstrings. The actual
        implementation of such a function would require parsing the function's signature and
        docstrings in the real world, which is beyond this simple example's scope.
    """
    pass  # This is a placeholder for the implementation.