本文介绍了在 python 模块文档字符串中放什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经阅读了 PEP 8 和 PEP 257,我为函数和类编写了很多文档字符串,但我我有点不确定模块文档字符串中应该包含什么.我想,至少,它应该记录模块导出的函数和类,但我也看到了一些列出作者姓名、版权信息等的模块. 有没有人有一个好的 python 文档字符串应该如何的例子结构化?

解决方案

想想有人在交互式解释器的提示下执行 help(yourmodule) — 他们想要做什么知道?(其他提取和显示信息的方法在信息量上大致相当于help).所以如果你在 x.py:

"""这个模块做废话."""类废话(对象):"""这门课真是胡说八道."""

然后:

>>>进口 x;帮助(x)

显示:

关于模块 x 的帮助:名称x - 这个模块做废话废话.文件/tmp/x.py班级__builtin__.object废话类 Blah(__builtin__.object)|这门课确实废话.||此处定义的数据和其他属性:||__dict__ = |实例变量字典(如果定义)||__weakref__ = <属性 '__weakref__' of 'Blah' 对象>|对对象的弱引用列表(如果已定义)

如您所见,这些组件的文档字符串中已经包含了关于类(以及函数,虽然我没有在这里展示)的详细信息;模块自己的文档字符串应该非常概括地描述它们(如果有的话),而是专注于模块作为一个整体可以为你做的事情的简明摘要,最好有一些经过文档测试的示例(就像函数和类一样,理想情况下应该有经过文档测试的示例)他们的文档字符串).

我看不出作者姓名和版权/许可证等元数据如何帮助模块的用户——它可以放在评论中,因为它可以帮助某人考虑是否重用或修改模块.

Ok, so I've read both PEP 8 and PEP 257, and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions and classes that the module exports, but I've also seen a few modules that list author names, copyright information, etc. Does anyone have an example of how a good python docstring should be structured?

解决方案

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

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

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

then:

>>> import x; help(x)

shows:

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)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

这篇关于在 python 模块文档字符串中放什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 03:12