【问题标题】:Pythonic way to find the name of global namespace imports查找全局命名空间导入名称的 Pythonic 方法
【发布时间】:2011-04-25 20:03:43
【问题描述】:

我正在尝试构建一些动态代码来解析文本文件,其中包含从模块顶部的导入命名的对象...现在我遍历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

【问题讨论】:

    标签: python introspection


    【解决方案1】:

    你想要globals()吗?

    【讨论】:

      【解决方案2】:

      你不能用吗

      globals()
      

      ?

      此外,是否有理由不明确指定要迭代的对象?这样,您就不会受到一些相关进口的“全局”“污染”。

      【讨论】:

      • 我将所有我关心的类重命名为_SomeObject... 然后用户的配置文件必须在使用前指定确切的对象名称;所以我认为使用这种技术是合理的。您还有其他建议吗?
      • @Mike:这当然只是个人喜好问题,但我可能仍会使用全局对象字典。 IMO,明确命名哪些对象可供用户使用,这比魔术“_”前缀(按照惯例用于“内部”,现在它被用作“ API 标记”)。 YMMV。
      猜你喜欢
      • 2014-12-02
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      相关资源
      最近更新 更多