给定一个包含以下内容的模块:
import stuff
from foo import Foo
from bar import *
CST = True
def func(): pass
如何定义函数get_defined_objects以便执行以下操作:
print(get_defined_objects('path.to.module'))
{'CST': True, 'func', <function path.to.module.func>}
现在,我能想象的唯一解决方案是读取原始模块文件,使用提取定义的名称,re.search(r'^(?:def|class )?(\w+)(?:\s*=)?'
然后导入模块,并找到的交集__dict__
。
有清洁剂吗?
您可以从这里开始使用ast
。请注意,尽管该代码应正确处理例如多个分配,但它并未涵盖所有可能的情况。例如ast
,如果您想访问已编译的代码,请考虑更仔细地研究的数据结构和API。
import ast
with open('module.py') as f:
data = f.read()
tree = ast.parse(data)
elements = [el for el in tree.body if type(el) in (ast.Assign, ast.FunctionDef, ast.ClassDef)]
result = {}
for el in elements:
if type(el) == ast.Assign:
for t in el.targets:
if type(el.value) == ast.Call:
result[t.id] = el.value.func.id + '()'
else:
for attr in ['id', 'i', 's']:
try:
result[t.id] = getattr(el.value, attr)
break
except Exception as e:
pass
elif type(el) == ast.FunctionDef:
result[el.name] = '<function %s>' % el.name
else:
result[el.name] = '<class %s>' % el.name
print result
#
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句