为什么命令式语气对文档字符串很重要?

Why is imperative mood important for docstrings?

pydocstyle 的错误代码 D401 显示为:First line should be in imperative mood

我经常 运行 遇到这样的情况:我写一个文档字符串,我的 linter 抛出这个错误,然后重写它——但这两个文档字符串在语义上是相同的。为什么对文档字符串有命令式的情绪很重要?

来自 check_imperative_mood 本身的文档字符串:

  """D401: First line should be in imperative mood: 'Do', not 'Does'.

   [Docstring] prescribes the function or method's effect as a command:
    ("Do this", "Return that"), not as a description; e.g. don't write
    "Returns the pathname ...".

(我们将忽略该文档字符串本身无法通过测试的讽刺意味。)

为了保持一致性。这可能源于提交消息 git 自动创建的事实,例如合并提交,也使用命令式语气。

为什么重要?因为这是 Python 文档字符串的明确约定,详见 PEP 257。它没有什么特别之处 - "Multiplies two integers and returns the product" 和 "Multiply two integers and return the product" 中的一个明显优于另一个,这对我来说似乎并不明显。但是在文档中有明确说明。

考虑以下文档字符串候选示例:

Make a row from a given bit string or with the given number of columns.

在英语中,这是一个完整的语法句子,以大写字母开头,以句号结尾。这是一个句子,因为它有一个主语(隐含地,"you"),一个宾语,"row," 和一个谓语(动词),"make."

现在考虑一个替代方案:

Makes a row from a given bit string or with the given number of columns.

在英语中,这是不合语法的。这是一个形容词短语,因此不应以大写字母开头,也不应以句号结尾。让我们解决这个问题:

makes a row from a given bit string or with the given number of columns

作为形容词短语,它的先行词---它的目标---并不明确。当然,我们知道它是 "docstringed," 的项目,但在语法上,它是悬空的。那是个问题。从美学上讲,它很丑,这是另一个问题。所以我们解决了一个问题,又增加了两个。

对于那些关心清晰、无歧义的语法英语交流的人来说,第一个建议显然更好。我猜这就是 Pythonistas 选择第一个提案的原因。总之,"Docstrings shall be complete, grammatical sentences, specifically in the imperative mood."

仅仅说它是关于约定或一致性是不完整的(否则,follow-up 问题将是“与什么一致?”)。

它实际上是来自规范 PEP 257 Docstring Conventions 的明确要求 - 尽管深埋在规范中。引用如下:

def kos_root():
    """Return the pathname of the KOS root directory."""
    ...

Notes:

  • The docstring is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...".

pydocstyle 文档字符串实际上是从上面的 PEP 257 段落中引用的。