Previous Lesson | Table of Contents | Next Lesson |
In the last lesson, we learned about comments and how they are very important documenting our code. In this lesson, we will learn about a special type of commenting for functions, also known as docstrings:
def f(a, b):
"""
Compute the sum of two numbers.
This is a special addition function only for certain inputs.
Please continue reading for an explanation of how.
Parameters
----------
a : int
The first number to add. Must be non-zero.
b : int
The second number to add.
Returns
-------
sum : int
The sum of the two numbers.
Raises
------
ValueError : the first number was zero.
"""
if a == 0:
raise ValueError("The first number must be non-zero")
return a + b
Although there is no specific format for docstrings, all docstrings are created via surrounding triple quotation marks (instead of single quotation marks). Inside, we generally have a description of the following:
- What the function does.
- The parameters to the function.
- What the function returns, if any.
- Potential errors that could be raised.
Our docstring above closely follows what’s known as the NumPy format. Here, we have the following:
- A sentence at the beginning explaining what the function does. You can have more description afterwards, but have a standalone sentence at the beginning.
- The parameters are described under a “Parameters” section, with each argument
being described with its type (in this case
int
, short for “integer”), followed by a description of that parameter. - The returned value is described under a “Returns” section, where the type of the return value is described as well as what the value signifies.
- Finally, because we explicitly raise an error when
a == 0
, we describe it under the “Raises” section, where we list the type of error raised (ValueError
) and how it can come about in our code.
There are many ways to form docstrings, but this way is used by a lot of major Python libraries and developers, so it’s a good one to start with. Using this one as a guide, let’s practice writing them.
Try writing a docstring for the following function:
def f(l): out = [] for i in l: out.append(str(i)) if len(out) == 0: raise ValueError("No elements collected") return out
Note that the type of l
is a list
. It’s best that you try to figure out
what the code is doing before writing the docstring.(solution).
Try writing a docstring for the following function:
def f(x): return [str(x), str(x)]
It’s best that you try to figure out what the code is doing before writing the docstring for the function. (solution).