本文介绍了查找全局名称空间导入名称的Python方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一些动态代码,该动态代码使用模块顶部的导入内容命名的对象来解析文本文件...现在,我遍历sys._getframe(0)
中的所有项以找到f_globals
.有找到f_globals
的更Python方式吗?
I am trying to build some dynamic code that parses a text file with objects named from the imports at the top of the module... right now I iterate through all items in sys._getframe(0)
to find f_globals
. Is there a more pythonic way of finding f_globals
?
import re
import sys
import inspect
## Import all Object models below
from Models.Network.Address import MacAddress as _MacAddress
from Models.Network.Address import Ipv4Address as _Ipv4Address
class Objects(object):
"Define a structure for device configuration objects"
def __init__(self):
"Initialize the Objects class, load appropriate objects"
self.objects = dict()
for name, members in inspect.getmembers(sys._getframe(0)):
if name == 'f_globals':
for modname, ref in members.items():
if re.search('^_[A-Za-z]', modname):
self.objects[modname] = ref
return
推荐答案
是否要 globals()
?
这篇关于查找全局名称空间导入名称的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!