Python has great in-built documentation that is available via the help
function. For example
l = ["cat", "dog", "fish"]
help(l)
You can add similar documentation to the functions that you write. You do this by adding in a documentation string as the first string after defining the function e.g.
def multiply(a, b):
"""This function returns the element-wise multiplication of the passed lists 'a' and 'b'"""
c = []
for x,y in zip(a,b):
c.append(x*y)
return c
multiply( [1,2,3], [4,5,6] )
help(multiply)
The documentation string should be placed between two sets of triple quotes ("""
). This is a convention that makes it easier to expand the documentation later, and that ensures that nothing you write in the documentation will be expanded or interpreted as Python.
Documentation should provide an easy to understand, and brief description of what the function does. It should not give information that is obvious by reading the function signature. For example, this is a bad piece of documentation.
def multiply(a, b):
"""function multiply(a,b) -> list"""
c = []
for x,y in zip(a,b):
c.append(x*y)
return c
help(multiply)
It is much better to say what the function does, and then what it returns (as this can't be seen from the signature). Good documentation would be
def multiply(a, b):
"""Calculates the element-wise multiplication of a and b, returning a list of the results"""
c = []
for x,y in zip(a,b):
c.append(x*y)
return c
help(multiply)
Your documentation can span over multiple lines. If you are describing the arguments, then you should use one line per argument, for example
def make_complex(real, imag=0):
"""Create and return a complex number
Keyword arguments:
real -- the real part of the number
imag -- the imaginary part of the number
"""
return (real,imag)
help(make_complex)
By convention, you will notice above that the last """
is placed on its own line if the documentation spans multiple lines. It is on the same line if the documentation is short.
In general, keep your documentation short, to the point, and avoid repeating obvious information. However, be precise, as this may be the only part of your code that somebody else reads before they use your function in their program.
A good suggestion is to look at documentation you like and try to copy that style. Also, look for code that you think is poorly documented, and try to avoid their mistakes. An example guide is PEP257