How to write meaningful docstrings?

Konrads picture Konrads · Mar 2, 2009 · Viewed 19.9k times · Source

What, in Your opinion is a meaningful docstring? What do You expect to be described there?

For example, consider this Python class's __init__:

def __init__(self, name, value, displayName=None, matchingRule="strict"):
    """
    name - field name
    value - field value
    displayName - nice display name, if empty will be set to field name
    matchingRule - I have no idea what this does, set to strict by default
    """

Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).

Answer

MrTopf picture MrTopf · Mar 2, 2009

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.