I’ve heard before that “modules are just classes too”. I have a few situations, mostly unit testing and interactive interpreter experimentation, where I would like to create a module in a variable without having to create any external files. I imagine something like:
>>> import sys
>>>
>>> m = sys.Module() # <- This is the class I want
>>> m.foo = 'bar'
>>> m
<module 'm' (instantiated)>
>>>
>>> sys.modules['testmodule'] = m
>>>
>>> import testmodule
>>> print testmodule.foo
bar
Note: I am aware that I can plug any object into the modules dict, but I’m specifically interested in creating a module instance
1 Answer