How do I instantiate a module in Python

python, python-2.7

Solution

>>> import types
>>> help(types.ModuleType)
>>> mymod = types.ModuleType("MyMod")
>>> mymod
<module 'MyMod' (built-in)>
>>>

Problem

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

Original source