我见过几种不同风格的Python文档字符串编写方式,哪些是最受欢迎的风格?
我见过几种不同风格的Python文档字符串编写方式,哪些是最受欢迎的风格?
Python文档字符串可以按照其他帖子所示的几种格式编写。然而,默认的Sphinx文档字符串格式未被提及,它基于reStructuredText(reST)。您可以在这篇博客文章中获取有关主要格式的一些信息。
请注意,PEP 287建议使用reST。
以下是文档字符串中主要使用的格式。
历史上,像javadoc一样的风格很普遍,因此将其作为Epydoc(使用称为Epytext
格式)生成文档的基础。
例如:
"""
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
"""
现在,更为普遍的格式是由Sphinx用于生成文档的reStructuredText(reST)格式。 注意:在JetBrains PyCharm中默认使用它(在定义方法后键入三个引号并按Enter)。它还是Pyment中的默认输出格式。
示例:
"""
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
"""
谷歌有自己的格式,通常被广泛使用。它也可以通过Sphinx解释(即使用Napoleon插件)。
示例:
"""
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.
"""
甚至更多例子
请注意,Numpy建议遵循他们自己的numpydoc,基于Google格式并可由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
"""
可以使用类似Pyment的工具自动生成Python项目的文档字符串,以便对尚未有文档说明的项目进行记录,或将现有的文档字符串(可以混合多种格式)从一种格式转换为另一种格式。
注意:这些示例来自Pyment文档。
Google风格指南包含了一份出色的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
我希望将其扩展,以在参数中包括类型信息,就像在这个Sphinx文档教程中描述的那样。例如:
def add_value(self, value):
"""Add a new value.
Args:
value (str): the value to add.
"""
pass
文档字符串规范在PEP-257中有比PEP-8更详细的内容。
然而,文档字符串似乎比代码的其他部分更加个人化。不同的项目将有自己的标准。
我倾向于始终包含文档字符串,因为它们往往能够非常快速地展示如何使用函数以及它的功能。
我喜欢保持一致性,无论字符串的长度如何。当缩进和间距一致时,我喜欢代码的外观。这意味着我使用:
def sq(n):
"""
Return the square of n.
"""
return n * n
结束:
def sq(n):
"""Returns the square of n."""
return n * n
在较长的文档字符串中,往往会忽略第一行的注释:
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
我觉得以这种方式开头的文档字符串很凌乱。
def sq(n):
"""Return the squared result.
...
"""返回平方结果"""
而不是"""返回平方结果"""
。尽管如此,我个人会像Tim在这里一样编写我的文档字符串,而不是遵循PEP的建议。 - Cam Jackson显然没人提到过:你也可以使用Numpy Docstring Standard,它在科学界得到了广泛应用。
Napoleon sphinx扩展程序(在@Nathan的回答中推荐)支持Numpy样式的文档字符串,并对两者进行了简短的比较。
最后给出一个基本示例,以便了解其外观:
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
ipython
来测试一个库,并且它使得读取文档字符串变得非常简单 —— 我所需要做的就是输入 your_module.some_method_im_curious_about?
,然后我就可以得到一个非常漂亮的输出,其中包括文档字符串。 - Thanatoshelp
函数,则可以查看文档字符串(即使只能访问已编译的模块)。个人认为,在选择文档字符串约定时应记住这一点(即它旨在按原样阅读)。 - skykingpydocstyle --select=D4 tmp.py
检查一系列文档字符串内容问题,包括部分命名。 - Finn Årup Nielsen
epydoc
、doxygen
和sphinx
呢?有没有人有统计数据,它们中的一个会取代其他选项吗?在这种情况下,太多的选择可能会造成困扰。 - sorindef foo(self, other):\n\t"""\n\t(空白行)\n\t:param other: \n\t:return:\n\t"""
- Matteo Ferla