从基于Python包的导入中获取docstrings

2024-06-28 19:34:45 发布

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

Python包中有几个模块:

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

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

^{pr2}$

我的问题是:如何以编程方式访问这些模块中每个定义函数的docstring?我见过others使用这种形式:

getattr(module, key). __doc__

但我不能让它为我工作。有什么想法吗?在

编辑:多一点背景。。。我们试图从python包中提取内容(其中一个重要的东西是docstring),目的是将其用作文档内容。我老板已经安排好了一些事情,我们正努力向他们提供信息。在

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

编辑2:以下是目前没有起作用的:

#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

编辑3:要了解docstring在哪里以及我们是如何组织的:

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!']在


Tags: 模块pyimport编辑packageinitmyscript
2条回答

也许你想要这样的东西:

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

但我不能保证这会得到所有的docstring。您可能需要递归地进入使用getattr检索的项。在

这里有一个递归版本(可能会得到比您想要的更多的结果),并且会因循环依赖而窒息:

^{pr2}$

使用inspect.getdoc(object)获取对象的docstring。 使用inspect.isfunction检查对象是否为函数。在

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

请注意检查.getdoc当对象没有docstring时返回None,因此如果函数没有docstring,代码将打印None。在

相关问题 更多 >