Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write meaningful docstrings?

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).

like image 542
Konrads Avatar asked Mar 02 '09 10:03

Konrads


People also ask

What is docstrings give example?

As mentioned above, Python docstrings are strings used right after the definition of a function, method, class, or module (like in Example 1). They are used to document our code. We can access these docstrings using the __doc__ attribute.

What are the three types of docstrings?

Let us know the most commonly used docstring formats out there in the wild, which are namely- Google, NumPy, and Sphinx docstring formats.

How do you structure a docstring?

The doc string line should begin with a capital letter and end with a period. The first line should be a short description. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.


2 Answers

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.

like image 104
MrTopf Avatar answered Sep 25 '22 17:09

MrTopf


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.
like image 44
Xolve Avatar answered Sep 25 '22 17:09

Xolve