最常见的 Python 文档字符串格式有哪些?

发布于 2024-09-27 10:47:38 字数 43 浏览 8 评论 0原文

我见过几种不同的 Python 文档字符串编写风格,最流行的风格是什么?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

蓝天 2024-10-04 10:47:38

格式

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

如今,可能更流行的格式是 使用的 reStructuredText (reST) 格式Sphinx 生成文档。
注意: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

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 格式且可由 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 文档

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

橘虞初梦 2024-10-04 10:47:38

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

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
永不分离 2024-10-04 10:47:38

文档字符串约定位于 PEP-257 中,比 PEP-8 更详细。

然而,文档字符串似乎比其他代码区域更加个性化。不同的项目会有自己的标准。

我倾向于总是包含文档字符串,因为它们倾向于快速演示如何使用该函数及其功能。

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

def sq(n):
    """
    Return the square of n. 
    """
    return n * n

Over:

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. 
    ...
街角迷惘 2024-10-04 10:47:38

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

拿破仑狮身人面像解析 Google 风格的文档字符串的扩展(在 @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
儭儭莪哋寶赑 2024-10-04 10:47:38

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

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

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.

梦情居士 2024-10-04 10:47:38

我建议使用 Vladimir Keleshev 的 pep257 Python 程序根据 PEP-257Numpy 文档字符串标准,用于描述参数、返回等。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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文