如何用参数记录方法?

时间:2022-10-01 21:26:03

How to document methods with parameters using Python's documentation strings?

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

EDIT: PEP 257 gives this example:

编辑: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
    ...

Is this the convention used by most Python developers ?

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

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

I was expecting something a little bit more formal such as

我想要一些更正式的东西,比如

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

Environement: Python 2.7.1

Environement:Python 2.7.1

7 个解决方案

#1


63  

Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.

根据我的经验,numpy docstring约定(PEP257超集)是最广泛的遵循约定的,工具(如Sphinx)也支持这些约定。

One example:

一个例子:

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

#2


47  

Since docstrings are free-form, it really depends on what you use to parse code to generate API documentation.

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

I would recommend getting familiar with the Sphinx markup, since it is widely used and is becoming the de-facto standard for documenting Python projects, in part because of the excellent readthedocs.org service. To paraphrase an example from the Sphinx documentation as a Python snippet:

我建议您熟悉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
   '''

This markup supports cross-referencing between documents and more. Note that the Sphinx documentation uses (e.g.) :py:attr: whereas you can just use :attr: when documenting from the source code.

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

Naturally, there are other tools to document APIs. There's the more classic Doxygen which uses \param commands but those are not specifically designed to document Python code like Sphinx is.

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

Note that there is a similar question with a similar answer in here...

注意,这里有一个类似的问题,有一个相似的答案……

#3


28  

Conventions:

约定:

Tools:

工具:


Update: Since Python 3.5 you can use type hints which is a compact, machine-readable syntax:

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

    """

The main advantage of this syntax is that it is defined by the language and that it's unambiguous, so tools like PyCharm can easily take advantage from it.

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

#4


9  

python doc strings are free-form, you can document it in any way you like.

python doc字符串是*格式的,您可以用任何您喜欢的方式来记录它。

Examples:

例子:

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

Now, there are some conventions, but python doesn't enforce any of them. Some projects have their own conventions. Some tools to work with docstrings also follow specific conventions.

现在,有一些约定,但是python不强制执行它们。有些项目有自己的惯例。使用docstring的一些工具也遵循特定的约定。

#5


8  

If you plan to use Sphinx to document your code, it is capable of producing nicely formatted HTML docs for your parameters with their 'signatures' feature. http://sphinx-doc.org/domains.html#signatures

如果您计划使用Sphinx为代码编制文档,那么它可以为您的参数生成格式良好的HTML文档,并具有“签名”功能。http://sphinx-doc.org/domains.html签名

#6


3  

The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.

正如这里的其他答案已经指出的那样,主流可能采用狮身人面像的方式,以便您以后可以使用狮身人面像生成那些花哨的文档。

That being said, I personally go with inline comment style occasionally.

也就是说,我个人偶尔会使用内联注释风格。

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()

One more example here, with some tiny details documented inline:

这里还有一个例子,一些细节被记录在内联文档中:

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

The benefits (as @mark-horvath already pointed out in another comment) are:

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

  • Most importantly, parameters and their doc always stay together, which brings the following benefits:
  • 最重要的是,参数和它们的doc总是在一起,这带来了以下好处:
  • Less typing (no need to repeat variable name)
  • 较少的输入(不需要重复变量名)
  • Easier maintenance upon changing/removing variable. There will never be some orphan parameter doc paragraph after you rename some parameter.
  • 更改/移除变量时更容易维护。在重命名某个参数之后,永远不会出现孤立参数doc段落。
  • and easier to find missing comment.
  • 更容易找到缺失的评论。

Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.

现在,一些人可能认为这种风格看起来“丑陋”。但是我要说“丑陋”是一个主观的词。更真实的说法是,这种风格不是主流,所以你可能不太熟悉它,因此不太舒服。再说一遍,“舒适”也是一个主观的词。但关键是,上面描述的所有好处都是客观的。如果你按照标准的方式去做,你就不可能达到目的。

Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.

希望将来有一天,文档生成器工具也能使用这种内联样式。这将推动领养。

PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.

PS:这个答案来自于我自己的偏好:每当我觉得合适的时候就使用内联注释。我也使用相同的内联样式来编写字典。

#7


2  

Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:

docstring只在交互式环境中有用,例如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

You can’t do this sort of thing with docstrings.

你不能用docstring做这种事情。

#1


63  

Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.

根据我的经验,numpy docstring约定(PEP257超集)是最广泛的遵循约定的,工具(如Sphinx)也支持这些约定。

One example:

一个例子:

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

#2


47  

Since docstrings are free-form, it really depends on what you use to parse code to generate API documentation.

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

I would recommend getting familiar with the Sphinx markup, since it is widely used and is becoming the de-facto standard for documenting Python projects, in part because of the excellent readthedocs.org service. To paraphrase an example from the Sphinx documentation as a Python snippet:

我建议您熟悉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
   '''

This markup supports cross-referencing between documents and more. Note that the Sphinx documentation uses (e.g.) :py:attr: whereas you can just use :attr: when documenting from the source code.

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

Naturally, there are other tools to document APIs. There's the more classic Doxygen which uses \param commands but those are not specifically designed to document Python code like Sphinx is.

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

Note that there is a similar question with a similar answer in here...

注意,这里有一个类似的问题,有一个相似的答案……

#3


28  

Conventions:

约定:

Tools:

工具:


Update: Since Python 3.5 you can use type hints which is a compact, machine-readable syntax:

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

    """

The main advantage of this syntax is that it is defined by the language and that it's unambiguous, so tools like PyCharm can easily take advantage from it.

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

#4


9  

python doc strings are free-form, you can document it in any way you like.

python doc字符串是*格式的,您可以用任何您喜欢的方式来记录它。

Examples:

例子:

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

Now, there are some conventions, but python doesn't enforce any of them. Some projects have their own conventions. Some tools to work with docstrings also follow specific conventions.

现在,有一些约定,但是python不强制执行它们。有些项目有自己的惯例。使用docstring的一些工具也遵循特定的约定。

#5


8  

If you plan to use Sphinx to document your code, it is capable of producing nicely formatted HTML docs for your parameters with their 'signatures' feature. http://sphinx-doc.org/domains.html#signatures

如果您计划使用Sphinx为代码编制文档,那么它可以为您的参数生成格式良好的HTML文档,并具有“签名”功能。http://sphinx-doc.org/domains.html签名

#6


3  

The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.

正如这里的其他答案已经指出的那样,主流可能采用狮身人面像的方式,以便您以后可以使用狮身人面像生成那些花哨的文档。

That being said, I personally go with inline comment style occasionally.

也就是说,我个人偶尔会使用内联注释风格。

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()

One more example here, with some tiny details documented inline:

这里还有一个例子,一些细节被记录在内联文档中:

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

The benefits (as @mark-horvath already pointed out in another comment) are:

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

  • Most importantly, parameters and their doc always stay together, which brings the following benefits:
  • 最重要的是,参数和它们的doc总是在一起,这带来了以下好处:
  • Less typing (no need to repeat variable name)
  • 较少的输入(不需要重复变量名)
  • Easier maintenance upon changing/removing variable. There will never be some orphan parameter doc paragraph after you rename some parameter.
  • 更改/移除变量时更容易维护。在重命名某个参数之后,永远不会出现孤立参数doc段落。
  • and easier to find missing comment.
  • 更容易找到缺失的评论。

Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.

现在,一些人可能认为这种风格看起来“丑陋”。但是我要说“丑陋”是一个主观的词。更真实的说法是,这种风格不是主流,所以你可能不太熟悉它,因此不太舒服。再说一遍,“舒适”也是一个主观的词。但关键是,上面描述的所有好处都是客观的。如果你按照标准的方式去做,你就不可能达到目的。

Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.

希望将来有一天,文档生成器工具也能使用这种内联样式。这将推动领养。

PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.

PS:这个答案来自于我自己的偏好:每当我觉得合适的时候就使用内联注释。我也使用相同的内联样式来编写字典。

#7


2  

Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:

docstring只在交互式环境中有用,例如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

You can’t do this sort of thing with docstrings.

你不能用docstring做这种事情。