tags:

views:

118

answers:

3

I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?

+1  A: 

Python's official styles are listed in PEP-8.

Amber
+5  A: 

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.

bstpierre
+6  A: 

Docstring conventions are in PEP-257 with much more detail than PEP-8.

However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.

I much tend to always include doctests, because they tend to demonstrate how to use the function and what it does very quickly.

I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:

def sq(n)
    """
    Returns the square of n. 
    """
    return n * n

Over:

def sq(n)
    """Returns the square of n."""
    return n * n

And tend to leave off commenting on the first line in longer docstrings:

def sq(n)
    """
    Returns the square of n, accepting all numeric types:

    >>> sq(10)
    100

    >>> sq(10.434)
    108.86835599999999

    Raises a TypeError when input is invalid:

    >>> sq(4*'435')
    Traceback (most recent call last):
      ...
    TypeError: can't multiply sequence by non-int of type 'str'

    """
    return n*n

Meaning I find docstrings that start like this to be messy.

def sq(n)
    """Returns the squared result. 
    ...
Tim McNamara