What Are the Most Common Python Docstring Formats

What are the most common Python docstring formats?

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

What style does PyCharm / IntelliJ use for Python docstrings?

Those are the Sphinx style doc strings.

Python has some strong opinions about doc strings, see PEP257.

Here is a full description of all of the doc string types in Python: What is the standard Python docstring format?

Can I format the docstring in python3

You have to edit the function __doc__ attribute after the fuction declaration

def run_tests(args):
pass

run_tests.__doc__ = """\
run tests on methods in {0}

usage: {0} --tests
""".format(__file__)

or make a decorator for doctring

def doc(arg):
"""Docstring decorator.

arg: Docstring text or object.
"""
import inspect

def decorator(func):
if type(arg) is str:
func.__doc__ = arg
elif inspect.isclass(arg):
func.__doc__ = arg.__doc__
else:
func.__doc__ = None

return func
return decorator

@doc(
f"""run tests on methods in {__file__}

usage: {__file__} --tests
"""
)
def run_tests(args):
pass

Python: Standard way to denote return and parameter types

There are mainly 3/4 formats competiting for the Python docstrings. See this tuto to have an overview.
The older format, now discontinued, is the Epytext for Epydoc based on Javadoc style. The probably more popular is the reStructuredText (reST) for Sphinx format. The Google style is also quite used. And of course the Numpydoc inspired from the Google style.

Concerning what should be the official/standard way you can refer to this topic.

Each format has its own way to represent the parameters types and return type. There follows some examples:

- Epytext / Javadoc

"""
@param param1: Description of param1
@type param1: type of param1

@return: description of returned value
@rtype: type of returned value
"""

- reST

"""
:param param1: Description of param1
:type param1: type of param1

:return: description of returned value
:rtype: type of returned value
"""

- Google

"""
Args:
param1(int): Description of parameter `param1`.
param2(str, optional): Description of a parameter. Defaults to None.

Returns:
bool: True or False depending on the result.
"""

- Numpydoc

"""
Parameters
----------
param1 : int
Description of parameter `param1`.
param2 : {'value1', 'value2'}
Description of a parameter with two possible values.

Returns
-------
int
Description of the returned value
"""

Converting

Note that if you have no docstrings or you want to change your docstring format for your Python project, you can use Pyment.

What is the common header format of Python files?

Its all metadata for the Foobar module.

The first one is the docstring of the module, that is already explained in Peter's answer.

How do I organize my modules (source files)? (Archive)

The first line of each file shoud be #!/usr/bin/env python. This makes it possible to run the file as a script invoking the interpreter implicitly, e.g. in a CGI context.

Next should be the docstring with a description. If the description is long, the first line should be a short summary that makes sense on its own, separated from the rest by a newline.

All code, including import statements, should follow the docstring. Otherwise, the docstring will not be recognized by the interpreter, and you will not have access to it in interactive sessions (i.e. through obj.__doc__) or when generating documentation with automated tools.

Import built-in modules first, followed by third-party modules, followed by any changes to the path and your own modules. Especially, additions to the path and names of your modules are likely to change rapidly: keeping them in one place makes them easier to find.

Next should be authorship information. This information should follow this format:

__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley",
"Matthew Wakefield"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Rob Knight"
__email__ = "rob@spot.colorado.edu"
__status__ = "Production"

Status should typically be one of "Prototype", "Development", or "Production". __maintainer__ should be the person who will fix bugs and make improvements if imported. __credits__ differs from __author__ in that __credits__ includes people who reported bug fixes, made suggestions, etc. but did not actually write the code.

Here you have more information, listing __author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ and __version__ as recognized metadata.

What is Python/Spyder equivalent of Javadoc?

This is how you write a docstring in python:

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

The format is not unified and can conform for example to:

  • reST
"""
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
"""
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.
"""
  • NumpyDoc
"""
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
"""


Related Topics



Leave a reply



Submit