17

我正在向我编写的包中添加一些(epydoc)文档,并且我遇到了很多重复自己多次的实例。

def script_running(self, script):
    """Return if script is running

    @param script: Script to check whether running

    @return: B{True} if script is running, B{False} otherwise
    @rtype: C{bool}
    """

PEP257说:

单线适用于非常明显的情况。

并且

函数或方法的文档字符串应总结其行为并记录其参数、返回值、副作用、引发的异常以及何时可以调用它的限制(如果适用)。


何时在单行(描述)和完整的参数/返回字段之间划清界限是否有一般指南或标准做法?

或者在生成文档时,我应该包括每个函数的每个适用字段,无论它看起来多么重复?

奖励问题:从语法上讲,描述script参数的最佳方式是什么?

4

2 回答 2

27

您正在寻找的一般准则在您引用的PEP257中是正确的,也许您只需要在实际中看到它。

您的函数非常适合单行文档字符串(“非常明显的案例”):

def script_running(self, script):
    """Check if the script is running."""

通常,如果您说一个函数正在检查某些内容,则意味着它将返回Trueor False,但如果您愿意,可以更具体:

def script_running(self, script):
    """Return True if the script is running, False otherwise."""

再一次集中在一条线上。

我可能还会更改您的函数的名称,因为无需强调函数在其名称(脚本)中的作用。函数名称应该是关于函数功能的甜美、简短和有意义的名称。可能我会选择:

def check_running(self, script):
    """Return True if the script is running, False otherwise."""

有时,函数名称的想象被所有的编码所累,但无论如何你都应该尽力做到最好。

对于多行示例,让我从google 指南中借用一个文档字符串:

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """

这可能是“总结其行为并记录其参数、返回值、副作用、引发的异常以及何时可以调用它的限制(所有如果适用)”的一种方式。

您可能也有兴趣查看这个pypi 项目示例,它打算用Sphinx记录。

我的 2 美分:指南旨在让您了解应该做什么和不应该做什么,但它们并不是您必须盲目遵循的严格规则。所以最后选择你觉得更好的。


我想清除另一个答案中所说的关于使用文档字符串达到最大行长的内容。

PEP8告诉你“将所有行限制为最多 79 个字符”,即使最后每个人都写了 80 个字符。

这是 80 个字符:

--------------------------------------------------------------------------------

这可能是一个极端情况,你真正需要的只是一个有点长的句子:

def my_long_doc_function(arg1, arg2):
    """This docstring is long, it's a little looonger than the 80 characters
    limit.
    
    """

就像一个单行文档字符串,这意味着它适用于非常明显的情况,但在您的编辑器(限制为 80 个字符)上是多行的。

于 2012-02-22T10:03:54.130 回答
4

我认为在为文档字符串添加扩展语法(即 epydoc/sphinx 标记)时,可能总是存在某种程度的重复。

我还要说这件事是主观的,而不是客观的。显式优于隐式,并且似乎更遵循 Python 的禅宗。

于 2012-02-22T09:45:14.530 回答