什么是标准的 Python 文档字符串格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3898572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the standard Python docstring format?
提问by Noah McIlraith
I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?
我已经看到在 Python 中编写文档字符串的几种不同风格,是否有官方或“商定”的风格?
采纳答案by daouzli
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.
Python 文档字符串可以按照其他帖子所示的几种格式编写。然而,没有提到默认的 Sphinx 文档字符串格式,它基于reStructuredText (reST)。您可以在这篇博文中获得一些有关主要格式的信息。
Note that the reST is recommended by the PEP 287
请注意,reST 是PEP 287推荐的
There follows the main used formats for docstrings.
以下是文档字符串的主要使用格式。
- Epytext
- 文本
Historically a javadoclike style was prevalent, so it was taken as a base for Epydoc(with the called Epytextformat) 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
- 休息
Nowadays, the probably more prevalent format is the reStructuredText(reST) format that is used by Sphinxto 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.
如今,可能更流行的格式是Sphinx用于生成文档的reStructuredText(reST) 格式。注意:它在 JetBrains PyCharm 中默认使用(在定义方法后键入三重引号并按 Enter)。默认情况下,它也用作 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 formatthat is often used. 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 numpydocbased on Google format and usable by Sphinx.
请注意,Numpy 建议遵循他们自己的基于 Google 格式并可供 Sphinx 使用的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
"""
Converting/Generating
转换/生成
It is possible to use a tool like Pymentto 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 文档
回答by bstpierre
回答by Tim McNamara
Docstring conventions are in PEP-257with much more detail than PEP-8.
文档字符串约定在PEP-257 中,比 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.
...
回答by Nathan
The Google style guidecontains an excellent Python style guide. It includes conventions for readable docstring syntaxthat offers better guidance than PEP-257. For example:
在谷歌的风格指南中包含一个优秀的Python风格指南。它包括可读文档字符串语法的约定,提供比 PEP-257 更好的指导。例如:
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:
我喜欢将其扩展为在参数中包含类型信息,如本Sphinx 文档教程 中所述。例如:
def add_value(self, value):
"""Add a new value.
Args:
value (str): the value to add.
"""
pass
回答by Colonel Panic
It's Python; anything goes. Consider how to publish your documentation. Docstrings are invisible except to readers of your source code.
它是 Python;什么都行。考虑如何发布您的文档。除了源代码的读者之外,文档字符串是不可见的。
People really like to browse and search documentation on the web. To achieve that, use the documentation tool Sphinx. It's the de-facto standard for documenting Python projects. The product is beautiful - take a look at https://python-guide.readthedocs.org/en/latest/. The website Read the Docswill host your docs for free.
人们真的很喜欢在网络上浏览和搜索文档。为此,请使用文档工具Sphinx。它是记录 Python 项目的事实上的标准。该产品很漂亮 - 看看https://python-guide.readthedocs.org/en/latest/。网站Read the Docs将免费托管您的文档。
回答by joris
As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.
显然没有人提到它:您也可以使用Numpy Docstring Standard。它在科学界被广泛使用。
- The specification of the formatfrom numpy together with an example
- You have a sphinx extension to render it: numpydoc
- And an example of how beautiful a rendered docstring can look like: http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
- 的格式的规范从numpy的连同示例
- 你有一个 sphinx 扩展来渲染它:numpydoc
- 以及呈现的文档字符串看起来有多漂亮的示例:http: //docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparisonof both.
用于解析 Google 样式文档字符串的 Napolean sphinx 扩展(在@Nathan 的回答中推荐)也支持 Numpy 样式文档字符串,并对两者进行了简短比较。
And last a basic example to give an idea how it looks like:
最后是一个基本示例,以了解它的外观:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
See Also
--------
otherfunc : some related other function
Examples
--------
These are written in doctest format, and should illustrate how to
use the function.
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
return True
回答by Finn ?rup Nielsen
I suggest using Vladimir Keleshev's pep257Python program to check your docstrings against PEP-257and the Numpy Docstring Standardfor describing parameters, returns, etc.
我建议使用 Vladimir Keleshev 的pep257Python 程序根据PEP-257和Numpy Docstring Standard检查您的文档字符串,以描述参数、返回等。
pep257 will report divergence you make from the standard and is called like pylint and pep8.
pep257 将报告您与标准的差异,并被称为 pylint 和 pep8。

