标准的Python docstring格式是什么?

2024-04-24 11:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中看到了几种不同的docstring编写风格,有正式的还是“一致同意”的风格?


Tags: 风格docstring
3条回答

文档字符串约定在PEP-257中比PEP-8详细得多。

然而,docstring似乎比其他代码领域更加个人化。不同的项目会有自己的标准。

我总是倾向于包含docstring,因为它们倾向于演示如何使用函数以及函数的运行速度。

我更喜欢保持事物的一致性,不管字符串的长度如何。我喜欢缩进和间距一致时的代码外观。也就是说,我用:

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

意思是我发现这样开始的docstring很混乱。

def sq(n):
    """Return the squared result. 
    ...

Google style guide包含一个优秀的Python风格指南。它包括conventions for readable docstring syntax比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 documentation tutorial中所述。例如:

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

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

格式

Python文档字符串可以按照其他文章所示的几种格式编写。但是,没有提到默认的Sphinx docstring格式,它基于reStructuredText(reST)。您可以在this blog post中获得一些有关主要格式的信息。

请注意,PEP 287推荐使用其余的

以下是docstring的主要使用格式。

-电子文本

从历史上看,类似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用来生成文档的structuredtext(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
"""

-谷歌

谷歌有自己的经常使用的format。它也可以由Sphinx解释(即使用Napoleon plugin)。

示例:

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

甚至more examples

-努姆皮多克

注意,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的工具自动将docstring生成到尚未记录的Python项目,或者将现有docstring(可以混合多种格式)从一种格式转换为另一种格式。

注:示例取自Pyment documentation

相关问题 更多 >