Python docstring templates


Template

def function_name(param1: Type1, param2: Type2, ...) -> ReturnType:
    """Brief description of the function.
 
    More detailed explanation of the function if necessary. This can span
    multiple lines as needed.
 
    Args:
        param1 (Type1): Description of param1.
        param2 (Type2): Description of param2.
        ...
 
    Returns:
        ReturnType: Description of the return value.
 
    Raises:
        ExceptionType: Explanation of the conditions under which this exception is raised.
 
    Example:
 
        >>> function_name(param1_value, param2_value)
        Expected output
    """
    ...

Example

With Type Hints

def add_numbers(num1: int, num2: int = 5) -> int:
    """Adds two numbers together.
 
    Args:
        num1 (int): The first number to add.
        num2 (int, optional): The second number to add. Defaults to 5.
 
    Returns:
        int: The sum of num1 and num2.
 
    Example:
        >>> add_numbers(3, 2)
        5
    """
    return num1 + num2

Without Type Hints

def add_numbers(num1, num2=5):
    """Adds two numbers together.
 
    Args:
        num1: The first number to add. Should be of type int.
        num2: The second number to add. Should be of type int. Defaults to 5.
 
    Returns:
        The sum of num1 and num2. The return value will be of type int.
 
    Example:
        >>> add_numbers(3, 2)
        5
    """
    return num1 + num2

Resources

Published May 24, 2023 | Updated May 24, 2023