2

我在 Python 包中有几个模块:

# my_package contents
__init__.py
module1.py
module2.py

在我的__init__.py中,我正在导入这些模块,以便在我的用户导入包后可以访问它们。

# __init__.py
import module1
import module2

我的问题是:我如何以编程方式访问每个模块中我定义的每个函数的文档字符串?我见过其他人使用这种形式:

getattr(module, key). __doc__

但我无法让它为我工作。有任何想法吗?

编辑:更多背景知识......我们正在尝试从我们的 python 包中提取内容(重要的事情之一是文档字符串),目的是将其用作文档的内容。我的老板已经设置了一些我们正在尝试使用的东西。

理想情况下,我想要一个package.module.function docstring结果

EDIT2:这是目前不起作用的:

#my package is named 'tpp'
import tpp

for script in dir(tpp):
    if not "__" in script: #not a builtin...
        docstrings1 = getattr( tpp, script).__doc__
        docstrings2 = " ".join(docstrings1.split())#clean out any newline chars
        print script, docstrings

EDIT3:要了解文档字符串的位置以及我们如何组织事物:

import inspect
import tpp

inspect.getdoc(tpp)
#returns None

inspect.getdoc(tpp.module1)
#returns None

inspect.getdoc(tpp.module1.function1)
#'DOCSTRING TEXT FOUND!'

**最终,我想得到一个类似 ['module1', 'function1', 'DOCSTRING TEXT FOUND!'] 的列表

4

2 回答 2

1

使用inspect.getdoc(object)获取对象的文档字符串。使用inspect.isfunction检查一个对象是否是一个函数。

import inspect
for variable in vars(module).values():
    if inspect.isfunction(variable):
        print(inspect.getdoc(variable))

请注意,当对象没有文档字符串时,inspect.getdoc 返回 None,因此如果函数没有文档字符串,代码将打印 None。

于 2012-07-25T14:41:24.607 回答
1

也许你想要这样的东西:

for script in dir(tpp):
    if not "__" in script: #not a builtin...
        docstrings1 = getattr( tpp, script).__doc__
        if docstrings1:  #objects without docstrings return None above, which can't be split.
            docstrings2 = " ".join(docstrings1.split())#clean out any newline chars
            print script, docstrings2

但我不保证这会得到所有的文档字符串。您可能需要递归地进入您使用 getattr 检索的项目。

这是一个递归版本(可能会比您想要的更多)并且会因循环依赖而窒息:

def get_all_doc(obj,indent=''):
    for item in filter(lambda x:not x.startswith('__'),dir(obj)):
        o=getattr(obj,item)
        print "{indent}{item} {doc}".format(indent=indent,
                                            item=item,
                                            doc=o.__doc__)
        get_all_doc(o,indent=indent+'   ')
于 2012-07-25T14:56:24.443 回答