Documenting Your Code

You have seen me putting in comments in most of my samples. These not only help other people understand your code but will also help you remember what you were thinking when you revisit your scripts months later to fix something. Comments not only explain your code, but also explain how to use your code or functions that you want others to use.

Python supports a method of creating documentation for your modules known as docstrings. Docstrings are strings written with triple quotes (“””) and can be placed at the top of modules and inside functions. When you type help(modulename), Python will print some nice documentation using the docstrings that you specified in your module.

Figure 13 - Documenting Your Code

There is an official specification on how you should format your docstrings, called PEP 0257. Many people don’t strictly follow this format and use a format that is supported by documentation generation tools like Doxygen, Epydoc, and Sphix. Formats include (taken from StackOverflow):

Epytext

"""
This is a javadoc style.

@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""

reST

"""
This is a reST style.

:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

Google

"""
This is an example of Google style.

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""

Numpydoc

"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.

Parameters
----------
first : array_like
    the 1st param name `first`
second :
    the 2nd param
third : {'value', 'other'}, optional
    the 3rd param, by default 'value'

Returns
-------
string
    a value in a string

Raises
------
KeyError
    when a key error
OtherError
    when an other error
"""

I recommend using one of these widely used formats instead of making one up on your own. You should try to put docstrings in your code as much as possible. It will save you and your coworkers a lot of time down the road.

Leave A Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

<code> For inline code.
[sourcecode] For multiline code.