问题:标准的Python文档字符串格式是什么?[关闭]

我已经看到了几种用Python编写文档字符串的样式,是否有正式或“同意的”样式?

I have seen a few different styles of writing docstrings in Python, is there an official or “agreed-upon” style?


回答 0

格式

可以按照其他文章所示的几种格式编写Python文档字符串。但是未提及默认的Sphinx文档字符串格式,该格式基于reStructuredText(reST)。您可以在此博客文章中获得有关主要格式的一些信息。

请注意,reST是PEP 287推荐的

以下是文档字符串的主要使用格式。

-Epytext

从历史上看,像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
"""

-reST

如今,可能更流行的格式是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
"""

– 谷歌

Google有自己常用的格式。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格式使用自己的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
"""

转换/生成

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

注意:这些示例摘自Pyment文档

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


回答 1

谷歌的风格指南中包含一个优秀的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

The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:

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:

def add_value(self, value):
    """Add a new value.

       Args:
           value (str): the value to add.
    """
    pass

回答 2

PEP-257中的文档字符串约定比PEP-8更为详细。

但是,文档字符串似乎比其他代码区域更具个性。不同的项目将有自己的标准。

我倾向于总是包含docstrings,因为它们倾向于演示如何使用该函数以及该函数的执行速度非常快。

无论字符串的长度如何,我都希望保持一致。我喜欢缩进和间距一致时的代码外观。这意味着,我使用:

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

Docstring conventions are in PEP-257 with much more detail than 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. 
    ...

回答 3

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

用于解析Google样式文档字符串的Napolean狮身人面像扩展名(在@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

As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.

The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.

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

回答 4

PEP-8是官方的python编码标准。它包含有关文档字符串的部分,该部分引用了PEP- 257-文档字符串的完整规范。

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 — a complete specification for docstrings.


回答 5

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

人们真的很喜欢浏览和搜索网络上的文档。为此,请使用文档工具Sphinx。这是记录Python项目的实际标准。该产品非常漂亮-请访问https://python-guide.readthedocs.org/en/latest/。“ 阅读文档 ”网站将免费托管您的文档。

It’s Python; anything goes. Consider how to publish your documentation. Docstrings are invisible except to readers of your source code.

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 Docs will host your docs for free.


回答 6

我建议使用Vladimir Keleshev的pep257 Python程序根据PEP-257Numpy Docstring Standard检查您的文档字符串,以描述参数,返回值等。

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

I suggest using Vladimir Keleshev’s pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.

pep257 will report divergence you make from the standard and is called like pylint and pep8.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。