Alex Rivera | Logout

Dynamic loading of python modules

Asked 2009-06-04T14:59:25.617
64

In python how do you dynamically add modules to a package while your program is running.

I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program:

import package

def doSomething(name):
    pkg = __import__("package." + name)
    mod = getattr(pkg, name)
    mod.doSomething()

How do I do this?

Edit
Report

1 Answer

10

One trick with Bastien's answer... The __import__() function returns the package object, not the module object. If you use the following function, it will dynamically load the module from the package and return you the module, not the package.

def my_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

Then you can do:

mod = my_import('package.' + name)
mod.doSomething()
answered 2009-06-04T17:02:57.113

Your Answer