在python模块docstring中放什么?

2024-05-17 08:20:32 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我已经阅读了PEP 8PEP 257,并且为函数和类编写了很多docstring,但是我有点不确定模块docstring中应该包含什么。我认为,至少,它应该记录模块导出的函数和类,但我也看到了一些列出作者姓名、版权信息等的模块。有没有人可以举一个例子说明一个好的python docstring应该如何构造?


Tags: 模块函数信息记录版权pep例子docstring
2条回答

想想有人在交互式解释器的提示下做help(yourmodule)-他们想知道什么?(其他提取和显示信息的方法在信息量方面大致相当于help)。因此,如果您在x.py中有:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

然后:

>>> import x; help(x)

显示:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

如您所见,这些类的详细信息(以及函数,尽管我在这里没有展示)已经包含在这些组件的docstring中;模块自己的docstring应该非常概括地描述它们(如果有的话),而应该集中在模块作为一个整体可以为您做什么的简明摘要上,理想情况下使用一些doctested示例(就像函数和类理想情况下应该在其docstring中包含doctested示例一样)。

我看不出诸如author name和copyright/license之类的元数据是如何帮助模块的用户的——它更愿意加入注释,因为它可以帮助人们考虑是否重用或修改模块。

引用specifications

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

函数或方法的docstring 是以句号结尾的短语。它将函数或方法的效果指定为命令(“Do this”,“Return that”),而不是描述;例如,不要编写“Return the pathname…”。函数或方法的多行docstring应总结其行为,并记录其参数、返回值、副作用、引发的异常以及何时可以调用它的限制(如果适用,全部)。应指出可选参数。应该记录关键字参数是否是接口的一部分。

相关问题 更多 >