This text is part of a Real Python tutorial by Leodanis Pozo Ramos.
Python allows you to add optional docstrings and annotations to your functions.
Docstrings are strings that you add at the beginning of a function to provide built-in documentation. They explain what a function does, what arguments it expects, and what it returns. Annotations let you optionally specify the expected types of arguments and return values, making your code clearer to readers and compatible with type-checking tools.
In this lesson, you’ll learn how to add and use both of these optional yet highly valuable features in your Python functions.
Docstrings
When the first statement in a function’s body is a string literal, it’s known as the function’s docstring.
You can use a docstring to supply quick documentation for a function. It can contain information about the function’s purpose, arguments, raised exceptions, and return values. It can also include basic examples of using the function and any other relevant information.
Below is an average() function showing a docstring in Google’s style and with doctest test examples:
def average(*args):
"""Calculate the average of given numbers.
Args:
*args (float or int): One or more numeric values.
Returns:
float: The arithmetic mean of the provided values.
Raises:
ZeroDivisionError: If no arguments are provided.
Examples:
>>> average(10, 20, 30)
20.0
>>> average(5, 15)
10.0
>>> average(7)
7.0
"""
return sum(args) / len(args)
Technically, docstrings can use any string quoting variant. However, the recommended and more common variant is to use triple quotes using double quote characters ("""), as shown above. If the docstring fits on one line, then the closing quotes should be on the same line as the opening quotes.
Multiline docstrings are used for lengthier documentation. A multiline docstring should consist of a summary line ending in a dot, a blank line, and finally, a detailed description. The closing quotes should be on a line by themselves.