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


当前回答

在类型提示回答(https://stackoverflow.com/a/9195565/2418922)的基础上,它提供了一种更好的结构化方式来记录参数类型,还有一种结构化的方式来记录参数的类型和描述:

def copy_net(
    infile: (str, 'The name of the file to send'),
    host: (str, 'The host to send the file to'),
    port: (int, 'The port to connect to')):

    pass

示例:https://pypi.org/project/autocommand/

其他回答

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

在类型提示回答(https://stackoverflow.com/a/9195565/2418922)的基础上,它提供了一种更好的结构化方式来记录参数类型,还有一种结构化的方式来记录参数的类型和描述:

def copy_net(
    infile: (str, 'The name of the file to send'),
    host: (str, 'The host to send the file to'),
    port: (int, 'The port to connect to')):

    pass

示例:https://pypi.org/project/autocommand/

约定:

PEP 257文档字符串约定 PEP 287 reStructuredText文档字符串格式

工具:

Epydoc:为Python自动生成API文档 autodoc -包括文档字符串中的文档 PyCharm对文档字符串有一些很好的支持


更新:从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`.

    """

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

Python文档字符串是自由形式的,你可以用任何你喜欢的方式来记录它。

例子:

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

现在,有一些约定,但是python没有强制执行它们。有些项目有自己的约定。一些处理文档字符串的工具也遵循特定的约定。

文档字符串只在交互环境中有用,例如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

你不能用文档字符串做这种事情。