如何使用参数记录方法?

Dav*_*tti 125 python documentation documentation-generation

如何使用Python的文档字符串记录带参数的方法?

编辑: PEP 257给出了这个例子:

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)

    """
    if imag == 0.0 and real == 0.0: return complex_zero
    ...
Run Code Online (Sandbox Code Playgroud)

这是大多数Python开发人员使用的约定吗?

Keyword arguments:
<parameter name> -- Definition (default value if any)
Run Code Online (Sandbox Code Playgroud)

我期待一些更正式的东西,比如

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    @param: real The real part (default 0.0)
    @param: imag The imaginary part (default 0.0)

    """
    if imag == 0.0 and real == 0.0: return complex_zero
    ...
Run Code Online (Sandbox Code Playgroud)

Environement:Python 2.7.1

ana*_*cat 106

由于文档字符串是自由格式的,它实际上取决于您使用什么来解析代码以生成API文档.

我建议熟悉Sphinx标记,因为它被广泛使用,并且正在成为记录Python项目的事实标准,部分原因在于优秀的readthedocs.org服务.要将Sphinx文档中的示例解释为Python代码段:

def send_message(sender, recipient, message_body, priority=1):
   '''
   Send a message to a recipient

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring
   '''
Run Code Online (Sandbox Code Playgroud)

此标记支持文档之间的交叉引用等.请注意,Sphinx文档使用(例如),:py:attr:而您可以:attr:在从源代码中记录时使用.

当然,还有其他工具可以记录API.有更多经典的Doxygen使用\param 命令,但那些并不是专门用来记录像Sphinx那样的Python代码.

请注意,这里有一个类似的问题类似的答案 ......

  • 这是PyCharm默认评论自动生成使用的样式 (9认同)
  • @Ereghard 紧凑总是更好,随着时间的推移你会习惯它。 (2认同)

Vla*_*hev 79

根据我的经验,numpy文档字符串约定(PEP257超集)是最广泛传播的遵循约定,也由工具支持,例如Sphinx.

一个例子:

Parameters
----------
x : type
    Description of parameter `x`.
Run Code Online (Sandbox Code Playgroud)

  • 当我尝试处理您建议的文档字符串时,Sphinx抱怨"严重:意外的部分标题" - 您知道如何让Sphinx更高兴吗? (5认同)
  • 这可能是问题提出时的最佳答案,但我认为截至目前(2017年末),狮身人面像已经取得了胜利. (5认同)
  • 实际上在"描述"之前缺少一个空格.我检查了numpy文档,因为我立即注意到并且想到_"等一下,为什么它是**三个**空格?这很奇怪.谁用三个空格?"_ (3认同)
  • 这更接近我的预期。不幸的是,我选择了普通的 PEP 257 并添加了我自己的约定(以丢失自动生成的 HTML/PDF 文档为代价)。但是,下次我会选择这个解决方案。谢谢。 (2认同)

Jak*_*cil 32

约定:

工具:


更新:从Python 3.5开始,您可以使用类型提示,这是一种紧凑的机器可读语法:

from typing import Dict, Union

def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
    """
    Explanation: this function takes two arguments: `i` and `d`.
    `i` is annotated simply as `int`. `d` is a dictionary with `str` keys
    and values that can be either `str` or `int`.

    The return type is `int`.

    """
Run Code Online (Sandbox Code Playgroud)

这种语法的主要优点是它由语言定义并且它是明确的,因此像PyCharm这样的工具可以轻松地利用它.

  • 虽然这个答案现在是最受欢迎的,但上述两个PEP都没有提供一个约定来指定方法的参数类型. (12认同)

nos*_*klo 11

python doc字符串是自由格式的,您可以以任何您喜欢的方式记录它.

例子:

def mymethod(self, foo, bars):
    """
    Does neat stuff!
    Parameters:
      foo - a foo of type FooType to bar with.
      bars - The list of bars
    """
Run Code Online (Sandbox Code Playgroud)

现在,有一些约定,但python不强制执行任何约定.有些项目有自己的约定.使用文档字符串的一些工具也遵循特定的约定.


小智 8

如果您计划使用Sphinx来记录您的代码,它可以使用"签名"功能为您的参数生成格式良好的HTML文档. http://sphinx-doc.org/domains.html#signatures


Ray*_*Luo 5

正如这里的其他答案已经指出的那样,主流可能采用Sphinx 方式,以便您稍后可以使用 Sphinx 生成那些精美的文档。

话虽如此,我个人偶尔也会使用内联评论风格。

def complex(  # Form a complex number
        real=0.0,  # the real part (default 0.0)
        imag=0.0  # the imaginary part (default 0.0)
        ):  # Returns a complex number.
    """Form a complex number.

    I may still use the mainstream docstring notation,
    if I foresee a need to use some other tools
    to generate an HTML online doc later
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    other_code()
Run Code Online (Sandbox Code Playgroud)

这里还有一个例子,其中内嵌了一些微小的细节:

def foo(  # Note that how I use the parenthesis rather than backslash "\"
          # to natually break the function definition into multiple lines.
        a_very_long_parameter_name,
            # The "inline" text does not really have to be at same line,
            # when your parameter name is very long.
            # Besides, you can use this way to have multiple lines doc too.
            # The one extra level indentation here natually matches the
            # original Python indentation style.
            #
            # This parameter represents blah blah
            # blah blah
            # blah blah
        param_b,  # Some description about parameter B.
            # Some more description about parameter B.
            # As you probably noticed, the vertical alignment of pound sign
            # is less a concern IMHO, as long as your docs are intuitively
            # readable.
        last_param,  # As a side note, you can use an optional comma for
                     # your last parameter, as you can do in multi-line list
                     # or dict declaration.
        ):  # So this ending parenthesis occupying its own line provides a
            # perfect chance to use inline doc to document the return value,
            # despite of its unhappy face appearance. :)
    pass
Run Code Online (Sandbox Code Playgroud)

好处(正如@mark-horvath 在另一条评论中已经指出的那样)是:

  • 最重要的是,参数及其文档始终保持在一起,这带来了以下好处:
  • 减少输入(无需重复变量名)
  • 更改/删除变量时更容易维护。重命名某个参数后,永远不会出现一些孤立参数文档段落。
  • 并且更容易找到缺失的评论。

现在,有些人可能会认为这种风格看起来“丑陋”。但我想说“丑”是一个主观词。更中性的说法是,这种风格不是主流,所以你可能会觉得不太熟悉,从而不太舒服。再次强调,“舒适”也是一个主观词。但重点是,上述所有好处都是客观的。如果你遵循标准方式,你就无法实现它们。

希望将来的某一天,会有一个文档生成器工具也可以使用这种内联样式。这将推动采用。

PS:这个答案源于我自己在认为合适的时候使用内联注释的偏好。我也使用相同的内联样式来记录字典