Pythonic way to find the name of global namespace imports

梦想与她 提交于 2019-12-08 11:58:11

问题


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

回答1:


Did you want globals()?




回答2:


Can't You just use

globals()

?

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.



来源:https://stackoverflow.com/questions/5782651/pythonic-way-to-find-the-name-of-global-namespace-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!