如何写docstring?

2020年8月30日 / 782次阅读 / Last Modified 2020年9月1日

代码就是最好的文档,python的docstring,应该是要好好编写和维护的。本文内容是对PEP257的理解和总结。PEP257只是说明了docstring的convention,要不要按照这个convention来写docstring,程序员有自由。但是如果按照这个convention来写docstring,能够得到一些好处,比如pydoc

import之后,docstring的内容,存放在对象的__doc__属性中。

docstring习惯上用 triple double quote (""") 括起来!

哪些对象需要写docstring?

package,module,function,class,method(class中的),都要写docstring。package的docstring写在__init__.py这个文件中,写法跟在module中写一样。

PEP257中提到的 attribute docstring 和 additional docstring,我暂时选择了忽略。保持简单很重要!

docstring写在什么位置

对应package的__init__.py文件和module(就是.py文件),docstring写在文件的最开始。如果有#!,写在#!后面。

其它对象的docstring,都写在对象定义位置的下一行。下面有例子。

对于class的docstring,PEP257中有说到一个细节,即写完docstring后,空一行,再写def __init__(self)。这里的空一行,应该是PEP8的内容,属于code layout。

oneline docstring

很简单,就一行。这样:""" 内容 """,所有符号都在一行内。

def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root
    ...

一般 package和module的docstring,不应该会写成oneline的。

multi-line docstring

多行docstring有一些说道:

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be used by automatic indexing tools; it is important that it fits on one line and is separated from the rest of the docstring by a blank line. The summary line may be on the same line as the opening quotes or on the next line. The entire docstring is indented the same as the quotes at its first line (see example below).

  • 多行docstring由一行summary和多行elaborate description组成,这两者之间一定要有一个空行;
  • summary就一行,但这一行可以写在"""后面,也可以换行写;

elaborate description部分,我看网上贴出来不同公司的风格,这些都是细节了。python自带的pydoc,貌似对中间的空行不做特别处理,但是有些更高级的工具会处理中间这个空行。所以,还是请保持这个空行吧,看着看着就习惯了。

如下这三种情况,都属于多行docstring:

def foo():
    """A multi-line

    docstring.
    """

def bar():
    """
    A multi-line

    docstring.
    """

def zxy():
    """
    A multi-line docstring, no more description.
    """

什么时候可以不写docstring?

写docstring,是为了用pydoc直接导出文档,代码就是你的文档。不过,也有情况可以不用写。

下划线开头的function, class和method,我觉得是可以不用写docstring的。因为在用pydoc导出的时候,下划线开头的这些对象,不会输出。习惯上这些都是内部使用的对象,根据情况,我觉得是可以不写docstring的。

-- EOF --

本文链接:https://www.pynote.net/archives/2427

相关文章

    留言区

    您的电子邮箱地址不会被公开。 必填项已用*标注


    前一篇:
    后一篇:

    More

    麦新杰的Python笔记

    Ctrl+D 收藏本页


    ©Copyright 麦新杰 Since 2019 Python笔记

    go to top