Python: subscript a module

痞子三分冷 提交于 2019-11-27 08:14:36

问题


I was trying to do something like this:

module.py

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

test.py

import module
print module['Monty']

I expected "MontyPython" to be printed. However, this doesn't work:

TypeError: 'module' object is not subscriptable 

Is it possible to create a subscriptable module in pure Python (i.e. without modifying its source code, monkey-patching, etc.)?


回答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

you may use ModModule(globals()) to replace the current module in sys.



来源:https://stackoverflow.com/questions/10438894/python-subscript-a-module

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