00:00 Now that you’ve seen the variety of ways that you can provide an interface to using your function, let’s talk about other ways that you can communicate to other programmers how your function is supposed to be used.
00:13 It’s considered good programming practice to provide documentation to other programmers on how to use your function: Information about what the function does, what it returns, if anything, and what parameters, if any, that it needs.
For example, here is a simple function to find the average of a collection of parameters. It’s included a docstring. It says
"""Returns the average of a list of numeric values.""" Typically, we use triple quotes (
""") using double quotation marks to write this string literal.
01:17 If the documentation fits on a single line, we begin and end with the triple quotes on that same line. On the other hand, if you use a multi-line string for your documentation, then the first part of the string appears on the first line under the function header, but then the docstring is closed with the triple quotes on a line by itself.
Here is another generic function called
foo(). It takes two parameters. We have a description that this performs a
foo transformation, where
bar represents the magnitude along one axis and
baz represents the change of magnitude along the other axis. So again, a string literal, which conventionally we use three double quotes to begin.
avg()’s docstring fits on a single line, so the ending triple quotes are on the same line. On the other hand,
foo()’s docstring is much longer, and so we have the closing quotes on a line by itself.
Notice where this documentation appears. Many Python editing programs will provide you the documentation when it sees you using that function name, and so we see this popup window showing the docstring for
foo() just as we’ve typed it.
03:49 There are many styles to docstrings. Which one you use can depend on a number of factors. If you’re involved with an existing project, it would be best to match the style that they use to create consistency throughout the project. For your own work, find one that suits you best.
Become a Member to join the conversation.