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 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 kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
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
Answer from daouzli on Stack Overflowcoding style - What are the most common Python docstring formats? - Stack Overflow
Is there a Sphinx reST Python docstring field for yields? - Stack Overflow
python - Utilizing Sphinx with reStructuredText formatted docstrings - Stack Overflow
What format do you use for your docstrings?
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 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 kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
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
Python 3.5 Iterator[] annotation
They offer a standardized Iterator[] syntax for this as documented at: https://docs.python.org/3/library/typing.html#typing.Generator
Before Python 3, I recommend that you use this syntax to make it easier to port later on:
def f():
"""
:rtype: Iterator[:class:`SomeClass`]
"""
yield SomeClass()
And after Python 3, use https://pypi.python.org/pypi/sphinx-autodoc-annotation with syntax:
from typing import Iterator
def f() -> Iterator[SomeClass]:
yield SomeClass()
I have reviewed the other answer and it doesn't in my opinion answer the question.
The way to document a generator, although not the best, is by using :return as in the rest of the docs. Use the description to give notice that it is a generator.
Yields from Google/Numpy style docs convert yields to return clauses.
https://bitbucket.org/RobRuana/sphinx-contrib/src/a06ae33f1c70322c271a97133169d96a5ce1a6c2/napoleon/sphinxcontrib/napoleon/docstring.py?at=default&fileviewer=file-view-default#docstring.py-678:680
The two formats are actually the same. This can be confusing but what's called the Info field lists can be considered the reST docstring syntax. If you look carefully at the version number it's been around since Sphinx version 0.4, next if we look at the current Sphinx change list it remits to a change list that predates version 1.0... The earliest mention there is:
Release 0.4 (Jun 23, 2008)
==========================
- Sphinx now interprets field lists with fields like
:param foo:in description units.
If we want to dig further back to the definition of the reST docstring syntax the archives of the Doc-SIG - Python Documentation Special Interest Group would be the way to go, but a good enough overview is given by PEP 256 - Rationale dated 01-Jun-2001. The document that emerged from then and is most frequently cited only makes a loose recommendation:
PEP 257 -- Docstring Conventions
Python is case sensitive and the argument names can be used for keyword arguments, so the docstring should document the correct argument names. It is best to list each argument on a separate line.
To summarize things, the reST docstring syntax consists simply of using reST Field Lists! (the NumPy and Google styles are just different styles of also writing reST Field Lists)!
Field List - reStructuredText Markup Specification
Field lists are mappings from field names to field bodies,
(...)
The interpretation of individual words in a multi-word field name is up to the application. The application may specify a syntax for the field name.
Syntax diagram (simplified):
+--------------------+----------------------+ | ":" field name ":" | field body | +-------+------------+ | | (body elements)+ | +-----------------------------------+
It's up to the application to specify the syntax of the field names; so what Sphinx documentation generator specifies for the 2 example syntaxes in the question is that they are equivalent (this does not necessarily hold if you change to a different documentation generator).
Thanks to @mzjin's answer in the comments: this link describes that it is possible since v0.4.
The below example is given in the link, which is exactly what I was looking for.
py:function:: send_message(sender, recipient, message_body, [priority=1])
"""
Send a message to a recipient
:param str sender: The person sending the message
:param str recipient: The recipient of the message
:param str message_body: The body of the message
:param priority: The priority of the message, can be a number 1-5
:type priority: integer or None
:return: the message id
:rtype: int
:raises ValueError: if the message_body exceeds 160 characters
:raises TypeError: if the message_body is not a basestring
"""
My company is currently deciding between using ReST or the Google style for writing docstrings. What do you all use? What do you like/dislike about it?