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
>>> import types
>>> help(types.ModuleType)
>>> mymod = types.ModuleType("MyMod")
>>> mymod
<module 'MyMod' (built-in)>
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With