1108

I have seen a few different styles of writing docstrings in Python, what are the most popular styles?

4

6 回答 6

1343

格式

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

- 休息

如今,可能更流行的格式是ReStructuredText (reST) 格式,Sphinx使用它来生成文档。注意:它在 JetBrains PyCharm 中默认使用(在定义方法后输入三引号并回车)。它也默认用作 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.
"""

更多示例

-Numpydoc

请注意,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
"""

转换/生成

可以使用Pyment 之类的工具为尚未记录的 Python 项目自动生成文档字符串,或者将现有的文档字符串(可以混合多种格式)从一种格式转换为另一种格式。

注意:示例取自Pyment 文档

于 2014-06-24T11:10:21.110 回答
351

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
于 2011-11-13T03:14:39.227 回答
243

文档字符串约定在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. 
    ...
于 2010-10-10T05:36:16.127 回答
66

显然没有人提到它:您也可以使用Numpy Docstring Standard。它在科学界被广泛使用。

用于解析 Google 样式文档字符串的 Napolean 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
于 2014-04-21T00:01:27.870 回答
12

它是 Python;一切顺利。考虑如何发布您的文档。除了源代码的读者之外,文档字符串是不可见的。

人们真的很喜欢在网络上浏览和搜索文档。为此,请使用文档工具Sphinx。它是记录 Python 项目的事实标准。该产品很漂亮 - 看看https://python-guide.readthedocs.org/en/latest/Read the Docs网站将免费托管您的文档。

于 2013-01-11T19:29:17.153 回答
8

我建议使用 Vladimir Keleshev 的pep257 Python 程序对照PEP-257和用于描述参数、返回等的Numpy Docstring 标准检查您的文档字符串。

pep257 将报告您与标准的差异,并且被称为 pylint 和 pep8。

于 2014-09-11T15:34:24.330 回答