从基于Python包的导入中获取docstring
我有几个Python包中的模块:从基于Python包的导入中获取docstring,python,Python,我有几个Python包中的模块: # my_package contents __init__.py module1.py module2.py 在我的\uuuu init\uuuuuu.py中,我正在导入这些模块,以便在用户导入包后可以访问它们 # __init__.py import module1 import module2 我的问题是:如何通过编程方式访问这些模块中每个已定义函数的docstring?我见过这样一种用法: getattr(module, key). __doc__
# my_package contents
__init__.py
module1.py
module2.py
在我的\uuuu init\uuuuuu.py
中,我正在导入这些模块,以便在用户导入包后可以访问它们
# __init__.py
import module1
import module2
我的问题是:如何通过编程方式访问这些模块中每个已定义函数的docstring?我见过这样一种用法:
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:要了解文档字符串的位置以及我们是如何组织的:
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!']的列表。用于获取对象的DOCSTRING。
用于检查对象是否为函数
import inspect
for variable in vars(module).values():
if inspect.isfunction(variable):
print(inspect.getdoc(variable))
请注意,当对象没有docstring时,inspect.getdoc返回None,因此如果函数没有docstring,代码将打印None。可能您需要类似以下内容:
import inspect
for variable in vars(module).values():
if inspect.isfunction(variable):
print(inspect.getdoc(variable))
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+' ')
不清楚为什么需要访问其中函数的docstring。你能澄清一下吗?(另外,您的导入语句示例不应该有尾随的
.py
s:)访问所有docstring的一个选项是pydoc my_package
。请提供更多关于你的实际目标的背景。“但我不能让它为我工作”——有什么不对,它会引起例外吗?有什么错误?@mgilson-更新了上面的示例谢谢你的回答,mgilson!正如您所怀疑的,这只检查模块作为一个整体,而不是模块中任何定义的函数(不知道我说的是否正确:)关于如何递归地获取其中的函数(最终是docstring)的任何想法?使用递归版本,我只是获取模块,而不是它们的内部函数&docstring。print语句给了我:“module1 None”然后是“module2 None”@JGraham——它主要对我有用。(我得到递归错误是因为我没有设置足够高的递归限制,或者我可能有循环依赖项)。您可以尝试打印出过滤器
表达式的结果,看看是否有启发性。谢谢您的帮助,这里。嗯,使用我的本地示例(参见上面的Edit1),我仍然只得到基本模块。有关如何组织数据的更多详细信息,请参见Edit2。。。我觉得我解释得不够好。谢谢你的回复,拉姆钱德拉。。。因此,如果我以您为例,使用我的包名(tpp)代替module
,代码永远不会进入打印语句。tpp
可能没有函数,它可能只有可调用项-您确定它有函数try vars(tpp)并检查您是否看到