python 文档字符串中参数描述的多行描述

Multi-line description of a parameter description in python docstring

所以,reStructuredText 是 the recommended way 用于 Python 代码 文档,如果你足够努力,你可以 find in the sphinx documentation 如何规范您的函数签名文档。所有给出的例子都是 单行,但是如果参数描述是多行的,如下所示 ?

def f(a, b):
    """ Does something with a and b

    :param a: something simple
    :param b: well, it's not something simple, so it may require more than eighty
              chars
    """

syntax/convention 是什么?我应该缩进还是不缩进?它会破坏 reSTructuredText 渲染吗?

只需在您希望换行的地方换行。

def f(a, b):
    """ Does something with a and b

    :param a: something simple
    :param b: well, it's not something simple, 
              so it may require more than eighty
              chars
    """

似乎如果相对于 :param: 指令缩进至少一级,它不会破坏 reSTructuredText 渲染。就个人而言,我更喜欢将所有附加行与该参数的第一个描述行对齐。 请注意,reST 也会忽略新行并在没有换行符的情况下呈现您的文本。

不幸的是,我找不到任何会提及此问题或给出多行 :param: 描述示例的来源。

是的,Sphinx 的缩进效果对您来说似乎很舒服,pep8 没有争论。此外,如果您不希望生成的文档中的描述是多行的,您可以使用 Python 传统换行符和 \:

 def f(a, b):
    """ Does something with a and b

    :param a: something simple
    :param b: well, it's not something simple, so it may require more \
              than eighty chars
    """

来自原始发帖人的良好研究成果。令人惊讶的是 canonical sphinx documentation does not give a multi-line example on params,尽管由于 79-character guideline in PEP8.

在实践中,考虑到您的参数名称本身通常是一个 word 甚至更长的 snake_case_words,以已经很长的 <4 or 8+ spaces> :param 为前缀,明智的做法是将下一个仅一级的行缩进(即 4 个空格),这与中提到的 "hanging indents" 样式匹配 PEP 8.

class Foo(object):
    def f(a, bionic_beaver, cosmic_cuttlefish):
        """ Does something.

        :param a: something simple
        :param bionic_beaver: well, it's not something simple, 
            so it may require more than eighty chars,
            and more, and more
        :param cosmic_cuttlefish:
            Or you can just put all your multi-line sentences
            to start with SAME indentation.
        """

PS:你可以看到它的实际效果,例如, here。 Sphinx 可以获取这些文档字符串并生成 docs 没有任何问题。

签名渲染基于 docutils field lists。 link 包含如何缩进的示例,例如,如果您希望项目描述是逐项列表或枚举列表。

看这里:

:Date: 2001-08-16
:Version: 1
:Authors: - Me
          - Myself
          - I
:Indentation: Since the field marker may be quite long, the second
   and subsequent lines of the field body do not have to line up
   with the first line, but they must be indented relative to the
   field name marker, and they must line up with each other.
:Parameter i: integer