查找全局命名空间导入名称的 Pythonic 方法
我正在尝试构建一些动态代码,用于解析一个文本文件,其中包含从模块顶部的导入中命名的对象...现在我迭代 sys._getframe(0)
中的所有项目找到f_globals
。有没有更Pythonic的方式来查找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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要
globals()
吗?Did you want
globals()
?你不能直接使用吗
?
此外,是否有理由不明确指定要迭代的对象?这样,您就不容易受到某些相关导入的“全局”“污染”。
Can't You just use
?
Moreover, is there a reason why not explicitly specify object to iterate over? That way, you are not prone to "globals" "pollution" by some correlated imports.