I have this module, wat.py
import re
import types
import sys
hello = "Hello World"
class MyModule(types.ModuleType):
def get_re(self):
return re
def get_hello(self):
return hello
sys.modules[__name__] = MyModule('wat')
And I run this code:
>>> import wat
>>> wat.get_hello()
None
>>> wat.get_re()
None
Why does this not work?
It doesn’t work because you effectively deleted your module when you reassigned its entry in
sys.modules. See my related question.To make it work, change the last line of your module to:
and it will work.
BTW, you don’t have to derive your class from
types.ModuleTypein order to put instances of it insys.modules[]. Entries insys.modulesdon’t have to be module objects (according to Alex Martelli).