How to write meaningful docstrings?

What should go there:

Anything that you can't tell from the method's signature. In this case the only bit useful is: displayName - if empty will be set to field name.


Check out numpy's docstrings for good examples (e.g. http://github.com/numpy/numpy/blob/master/numpy/core/numeric.py).

The docstrings are split into several sections and look like this:

Compute the sum of the elements of a list.

Parameters
----------
foo: sequence of ints
   The list of integers to sum up.

Returns
-------
res: int
   sum of elements of foo

See also
--------
cumsum:  compute cumulative sum of elemenents

From PEP 8:

Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257.

  • Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the "def" line.
  • PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, and preferably preceded by a blank line.
  • For one liner docstrings, it's okay to keep the closing """ on the same line.

I agree with "Anything that you can't tell from the method's signature". It might also mean to explain what a method/function returns.

You might also want to use Sphinx (and reStructuredText syntax) for documentation purposes inside your docstrings. That way you can include this in your documentation easily. For an example check out e.g. repoze.bfg which uses this extensively (example file, documentation example).

Another thing one can put in docstrings is also doctests. This might make sense esp. for module or class docstrings as you can also show that way how to use it and have this testable at the same time.