如何使用参数记录方法?

问题描述 投票:112回答:7

如何使用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
    ...

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

Keyword arguments:
<parameter name> -- Definition (default value if any)

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

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

环境:Python 2.7.1

python documentation documentation-generation
7个回答
74
投票

根据我的经验,numpy docstring conventions(PEP257超集)是最广泛传播的遵循惯例,也得到了工具的支持,例如Sphinx

一个例子:

Parameters
----------
x : type
    Description of parameter `x`.

83
投票

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

我建议熟悉Sphinx markup,因为它被广泛使用,并且正在成为记录Python项目的事实标准,部分原因在于优秀的readthedocs.org服务。从Sphinx文档中的paraphrase an example作为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
   '''

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

当然,还有其他工具来记录API。有更经典的Doxygen使用\param commands,但这些并不是专门用于记录像Sphinx那样的Python代码。

请注意,这里有一个带similar questionsimilar answer ......


32
投票

约定:

工具:


更新:从Python 3.5开始,您可以使用type hints,它是一种紧凑的机器可读语法:

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

    """

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


10
投票

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

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


8
投票

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


2
投票

主流是,正如其他已经指出的答案,可能与Sphinx way一起使用,以便您可以使用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()

这里还有一个例子,内联记录了一些微小的细节:

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

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

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

现在,有些人可能认为这种风格看起来“丑陋”。但我会说“丑陋”是一个主观词。一种更为中性的方式就是说,这种风格不是主流,所以它可能看起来不太熟悉,因此不太舒服。同样,“舒适”也是一个主观词。但重点是,上述所有好处都是客观的。如果按照标准方式,则无法实现它们。

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

PS:这个答案源于我自己喜欢在我认为合适时使用内联评论。我也使用same inline style to document a dictionary


1
投票

文档字符串仅在交互式环境中有用,例如Python shell。在记录不会以交互方式使用的对象时(例如内部对象,框架回调),您也可以使用常规注释。这是我用来悬挂项目的缩进注释的样式,每个都在各自的行上,所以你知道评论适用于:

def Recomputate \
  (
    TheRotaryGyrator,
      # the rotary gyrator to operate on
    Computrons,
      # the computrons to perform the recomputation with
    Forthwith,
      # whether to recomputate forthwith or at one's leisure
  ) :
  # recomputates the specified rotary gyrator with
  # the desired computrons.
  ...
#end Recomputate

你不能用docstrings做这种事情。

© www.soinside.com 2019 - 2024. All rights reserved.