Python和Sphinx:多行谷歌风格文档字符串中的项目符号列表

25

我目前正在使用Sphinx文档化我的Python项目。在多行docstring的部分包含一个项目列表时,我遇到了一个问题。

我想包括一个带有项目符号的列表,但其中一个项目非常长。 我希望:

  • 列表能够通过Sphinx正确呈现
  • 但同时也要遵守PEP8关于行长度(<79)的规定

您会为这个docstring提供什么建议?

class geography():
""" Class defining a geography (cities and distance matrix)

This class implements a geography with a list of named cities with their
associated coordinates in a plane. Helper functions enable to :

- give a visual representation of that geography
- give a visual representation of the distance matrix
- give a visual representation of a configuration, a configuration being the repartition of some or all cities in pools

...

最后一行字符超过了79个字符。

然后通过Sphinx渲染注释。添加换行符会破坏Sphinx的项目符号列表。

2个回答

30
你可以像这样打断项目列表,只需将续行与前面的文本对齐即可:

你可以打断项目列表,只需将续行与前面的文本对齐即可:

- give a visual representation of that geography
- give a visual representation of the distance matrix
- give a visual representation of a configuration, a configuration being the
  repartition of some or all cities in pools

谢谢你的回答,Stephen。我会尽快抽出5分钟来尝试,并保持与你的沟通。 祝好, Pierre - Pierre Massé
太棒了!这个方法非常有效,我的文档仍然很好地构建,并且我现在符合PEP 8标准。我将为非项目列表添加附加注释,因为我成功应用了类似的解决方案。 - Pierre Massé

7

@Stephen Rauch提供的解决方案非常完美。我只想补充一点,它也适用于非项目符号列表。我曾经遇到一个类似的问题,即函数或方法参数的注释。例如:

def permute_array(arr, seq):
""" Function to "square permute" a 2D array

This function's purpose is to enable distance matrices permutations. That 
is, for example, permute both lines and columns of the array so as to 
reorder a distance matrix.

Args:
    arr (numpy array): the array to permute. It should be square of size n.
    seq (iterable of int): a permutation of range(n) (should be of length n and contain every integer from 0 to n-1)

最后一行太长了。

然而,“相同缩进级别”的换行符会破坏漂亮的sphinx方法文档:

    Args:
        arr (numpy array): the array to permute. It should be square of size n.
        seq (iterable of int): a permutation of range(n) (should be of length n
        and contain every integer from 0 to n-1)

糟糕的文档结构

然而,使用缩进进行换行效果很好。

    Args:
        arr (numpy array): the array to permute. It should be square of size n.
        seq (iterable of int): a permutation of range(n) (should be of length n
            and contain every integer from 0 to n-1)

精美的文档

(注:该链接为图片链接,无法翻译)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接