Function documentation
Now, have you been commenting your code? 😀
It will also be good practice to document your functions too. It should explain:
- What the function does
- What parameters are available, and what type would you expect it to be
- What the function returns
Without this, imagine how you will have to figure out what each input parameter is for (by wading through the code!)
It is a good practice to actually document your functions as you develop your code, rather than postponing it to after you have completed your code (“now, what is this parameter meant to do again?”)
docstring
It is conventional to use docstring
s for documenting functions.
docstring
s are surrounded by triple quotes ("""
) - sounds familiar?
They must be placed in the first line (can be a single line or multi-line).
Recommended: leave a blank line after the docstring, but do not leave one before the docstring.
You should describe each parameter (and refer to them by name).
You should also say what is (if any) the return value of the function.
You can also state any assumptions the function may have.
In its simplest form:
def square(x):
""" returns the square of x """
return x ** 2
print(square.__doc__) # This will print out your documentation
The two dominant style of docstrings are Google style and Numpy style docstrings. Both have their advantages and disadvantages. Just choose one style that best fits your needs and be consistent.
Of course, you can only develop your own style. As usual, everything is a guideline, not a hard rule!
I’ve reproduced both styles from this page.
Google style:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
Returns:
bool: Description of return value
"""
return True
Numpy style:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
"""
return True
pydoc
You can also use the pydoc module to generate your documentations, perhaps as an HTML. See the link if you are interested, but this is not important for this course.