【问题标题】:Python: subscript a modulePython:下标一个模块
【发布时间】:2012-05-13 09:52:47
【问题描述】:

我试图做这样的事情:

module.py

def __getitem__(item):
    return str(item) + 'Python'

test.py

import module
print module['Monty']

我希望打印“MontyPython”。但是,这不起作用:

TypeError: 'module' object is not subscriptable 

是否可以在纯 Python 中创建可下标的模块(即不修改其源代码、猴子补丁等)?

【问题讨论】:

  • 我正在编写一个需要从各个地方访问某个全局​​状态的应用程序。我认为有这样的东西会很酷:import state; state[something_specific] = new_stuff 而不是from state_class import state; ...
  • 我认为这种酷炫不值得付出努力。继续使用 dot 语法。在我看来,它要好得多。

标签: python module subscript


【解决方案1】:
>>> class ModModule(object):
    def __init__(self, globals):
        self.__dict__ = globals
        import sys
        sys.modules[self.__name__] = self
    def __getitem__(self, name):
        return self.__dict__[name]


>>> m = ModModule({'__name__':'Mod', 'a':3})
>>> import Mod
>>> Mod['a']
3

# subclassing the actual type won't work
>>> class ModModule(types.ModuleType):
    def __init__(self, globals):
        self.__dict__ = globals
        import sys
        sys.modules[self.__name__] = self
    def __getitem__(self, name):
        return self.__dict__[name]


>>> m = ModModule({'__name__':'Mod', 'a':3})

Traceback (most recent call last):
  File "<pyshell#114>", line 1, in <module>
    m = ModModule({'__name__':'Mod', 'a':3})
  File "<pyshell#113>", line 3, in __init__
    self.__dict__ = globals
TypeError: readonly attribute

您可以使用 ModModule(globals()) 替换 sys 中的当前模块。

【讨论】:

    猜你喜欢
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多