Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I instantiate a module in Python

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

like image 856
Hubro Avatar asked Dec 16 '22 22:12

Hubro


1 Answers

>>> import types
>>> help(types.ModuleType)
>>> mymod = types.ModuleType("MyMod")
>>> mymod
<module 'MyMod' (built-in)>
>>>
like image 162
SingleNegationElimination Avatar answered Jan 03 '23 08:01

SingleNegationElimination