>>> 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 の現在のモジュールを置き換えることができます。