如何为pydoc定义“模块文档”?

1 投票
2 回答
910 浏览
提问于 2025-04-16 00:12

一些Python模块的pydoc文档(比如mathsys)里有一个“模块文档”部分,里面有个很有用的链接,指向一些HTML格式的文档:

Help on module math:

NAME
    math

FILE
    /sw/lib/python2.6/lib-dynload/math.so

MODULE DOCS
    /sw/share/doc/python26/html/math.html

那么,如何在自己的模块中加入这样的部分呢?

更一般来说,有没有地方可以查到pydoc识别的变量的文档呢?

我在源代码里找不到这些信息,因为math模块是一个共享库,而在我的机器上(OS X)sys模块是内置在Python里的……任何帮助都非常感谢!

2 个回答

0

模块文档通常指的是模块的文档字符串。这个文档字符串是一个普通的文本(或者重构文本),通常放在模块的最上面。下面是一个例子。

"""
Module documentation.
"""

def bar():
    print "HEllo"

这适用于纯Python模块。

对于编译的扩展模块(比如 math),在初始化模块时,你需要把模块的文档字符串(作为一个Python字符串)作为第三个参数传递给 Py_InitModule3。这样做会把这个字符串设置为模块的文档字符串。你可以在数学模块的源代码中看到这个操作,在这里

3

经过查看pydoc模块的代码,我觉得“模块文档”这个链接只适用于标准模块,而不适用于自定义模块。

这里是相关的代码:

def getdocloc(self, object):
    """Return the location of module docs or None"""

    try:
        file = inspect.getabsfile(object)
    except TypeError:
        file = '(built-in)'

    docloc = os.environ.get("PYTHONDOCS",
                            "http://docs.python.org/library")
    basedir = os.path.join(sys.exec_prefix, "lib",
                           "python"+sys.version[0:3])
    if (isinstance(object, type(os)) and
        (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                             'marshal', 'posix', 'signal', 'sys',
                             'thread', 'zipimport') or
         (file.startswith(basedir) and
          not file.startswith(os.path.join(basedir, 'site-packages'))))):
        if docloc.startswith("http://"):
            docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
        else:
            docloc = os.path.join(docloc, object.__name__ + ".html")
    else:
        docloc = None
    return docloc

返回值为None会被理解为空的“模块文档”部分。

撰写回答