5) g. Function Annotations

In the beginning of this course you learned how to add comments to your code. In this section you will learn how to document functions properly.

You can a docstring to a function by adding text surrounded by triple quotes right after the function signature. Take a look at this example.

By adding this docstring you will make it easier for other people to understand your code and the purpose behind it.

But we can add more information. You can also specify what the function’s parameters are and what they mean as well as what the function returns.

There are several docstring styles that are accepted in the Python development community. The example shown below uses the Google documentation style.

You can also see the docstring if you pass a function into the help function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
help(my_function)

Output:
Help on function my_function in module __main__:

my_function(items, prefix, postfix='')
    This function prints out items from a given list with specified prefix
    and postfix

    Parameters:
        items (list): A list of items to print out.
        prefix (str): A string to add before each item.
        postfix (str): A string to add after each item.
            (default is "")

    Returns:
        None