Importing a Dynamically Generated Module
Credit: Anders Hammarquist
Problem
You have code in either compiled or source form and need to wrap it
in a module, possibly adding it to sys.modules as
well.
Solution
We build a new module object, optionally add it to
sys.modules, and populate it with an
exec statement:
def importCode(code, name, add_to_sys_modules=0):
""" code can be any object containing code -- string, file object, or
compiled code object. Returns a new module object initialized
by dynamically importing the given code and optionally adds it
to sys.modules under the given name.
"""
import imp
module = imp.new_module(name)
if add_to_sys_modules:
import sys
sys.modules[name] = module
exec code in module._ _dict_ _
return moduleDiscussion
This recipe lets you import a module from code that is dynamically
generated or obtained. My original intent for it was to import a
module stored in a database, but it will work for modules from any
source. Thanks to the flexibility of the exec
statement, the
importCode
function can accept code in many forms: a string of source
(implicitly compiled), a file object (ditto), or a previously
compiled code object, for example.
The addition of the newly generated module to
sys.modules is optional. You
shouldn’t normally do this for such dynamically
obtained code, but there are exceptions—for example, when
import statements for the
module’s name are later executed, and
it’s important that they’re
retrieved from sys.modules. Note that if you want the ...