ActiveState Code

Recipe 82234: Importing a dynamically generated module


This recipe will let you import a module from code that is dynamically generated. My original use for it was to import a module stored in a database, but it will work for modules from any source.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Importing a dynamically generated module

def importCode(code,name,add_to_sys_modules=0):
    """
    Import dynamically generated code as a module. code is the
    object containing the code (a string, a file handle or an
    actual compiled code object, same types as accepted by an
    exec statement). The name is the name to give to the module,
    and the final argument says wheter to add it to sys.modules
    or not. If it is added, a subsequent import statement using
    name will return this module. If it is not added to sys.modules
    import will try to load it in the normal fashion.

    import foo

    is equivalent to

    foofile = open("/path/to/foo.py")
    foo = importCode(foofile,"foo",1)

    Returns a newly generated module.
    """
    import sys,imp

    module = imp.new_module(name)

    exec code in module.__dict__
    if add_to_sys_modules:
        sys.modules[name] = module

    return module

# Example
code = \
"""
def testFunc():
    print "spam!"

class testClass:
    def testMethod(self):
        print "eggs!"
"""

m = importCode(code,"test")
m.testFunc()
o = m.testClass()
o.testMethod()

Comments

  1. 1. At 3:56 p.m. on 30 apr 2002, Irmen de Jong said:

    This doesn't work with packages. This obviously doesn't work when you're dealing with packages. For instance, importCode(code,'my.packaged.module') won't work.

Sign in to comment