What is the standard Python docstring format? [closed] What is the standard Python docstring format? [closed] python python

What is the standard Python docstring format? [closed]


Formats

Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST). You can get some information about the main formats in this blog post.

Note that the reST is recommended by the PEP 287

There follows the main used formats for docstrings.

- Epytext

Historically a javadoc like style was prevalent, so it was taken as a base for Epydoc (with the called Epytext format) to generate documentation.

Example:

"""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

Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation.Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.

Example:

"""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

Google has their own format that is often used. It also can be interpreted by Sphinx (ie. using Napoleon plugin).

Example:

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

Even more examples

- Numpydoc

Note that Numpy recommend to follow their own numpydoc based on Google format and usable by Sphinx.

"""My numpydoc description of a kindof very exhautive numpydoc format docstring.Parameters----------first : array_like    the 1st param name `first`second :    the 2nd paramthird : {'value', 'other'}, optional    the 3rd param, by default 'value'Returns-------string    a value in a stringRaises------KeyError    when a key errorOtherError    when an other error"""

Converting/Generating

It is possible to use a tool like Pyment to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.

Note: The examples are taken from the Pyment documentation


The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:

def square_root(n):    """Calculate the square root of a number.    Args:        n: the number to get the square root of.    Returns:        the square root of n.    Raises:        TypeError: if n is not a number.        ValueError: if n is negative.    """    pass

I like to extend this to also include type information in the arguments, as described in this Sphinx documentation tutorial. For example:

def add_value(self, value):    """Add a new value.       Args:           value (str): the value to add.    """    pass


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 tend to always include docstrings, 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):    """    Return 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):    """    Return 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):    """Return the squared result.     ...


matomo