2012-05-03 76 views
0

我試圖做這樣的事情:的Python:下一個模塊

module.py

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

test.py

import module 
print module['Monty'] 

我的預期「 MontyPython「將被打印。然而,這不起作用:

TypeError: 'module' object is not subscriptable 

是否有可能建立在純Python一標化的模塊(即無需修改其源代碼,猴子,修補等)?

+0

你爲什麼要這樣做? – cobie

+0

我正在編寫一個應用程序,需要從各個地方訪問特定的全局狀態。我認爲這樣做會很酷: 'import state; state [something_specific] = new_stuff' than 'from state_class import state; ...' – Pastafarianist

+0

我不認爲這種冷靜是值得的。只要繼續* dot *語法即可。在我看來,它更好。 – cobie

回答

2
>>> 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中的當前模塊。