Formats (格式)
Python docstrings can be written following several formats as the other posts showed. (可以按照其他文章所示的几种格式编写Python文档字符串。) However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST) . (但是,未提及默认的Sphinx文档字符串格式,该格式基于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 (请注意,reST是PEP 287推荐的)
There follows the main used formats for docstrings. (以下是文档字符串的主要使用格式。)
- Epytext (-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. (从历史上看,像Javadoc这样的样式很普遍,因此它被用作Epydoc (称为Epytext
格式)生成文档的基础。)
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 (-reST)
Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation. (如今,可能更流行的格式是Sphinx用于生成文档的reStructuredText (reST)格式。) Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). (注意:它在JetBrains PyCharm中默认使用(在定义方法后键入三引号,然后按Enter键)。) It is also used by default as output format in Pyment. (默认情况下,它也用作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. (Google有自己常用的格式 。) It also can be interpreted by Sphinx (ie. using Napoleon plugin ). (Sphinx也可以解释它(即使用Napoleon插件 )。)
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 (-Numpydoc)
Note that Numpy recommend to follow their own numpydoc based on Google format and usable by Sphinx. (请注意,Numpy建议根据Google格式使用自己的numpydoc ,并可由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. (可以使用诸如Pyment之类的工具自动为尚未记录的Python项目生成文档字符串,或将现有文档字符串(可以混合多种格式)从一种格式转换为另一种格式。)
Note: The examples are taken from the Pyment documentation (注意:这些示例摘自Pyment文档)