开发者

Pythonic way to find the name of global namespace imports

开发者 https://www.devze.com 2023-02-28 20:27 出处:网络
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_globa

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):
    开发者_如何学Python    "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


Did you want globals()?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号