查找全局命名空间导入名称的 Pythonic 方法

发布于 2024-11-03 07:09:38 字数 850 浏览 3 评论 0原文

我正在尝试构建一些动态代码,用于解析一个文本文件,其中包含从模块顶部的导入中命名的对象...现在我迭代 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔女人霸气范 2024-11-10 07:09:38

您想要 globals() 吗?

Did you want globals()?

大海や 2024-11-10 07:09:38

你不能直接使用吗

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文