Dynamic loading of python modules

No Name picture No Name · Jun 4, 2009 · Viewed 61.7k times · Source

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?

Answer

S.Lott picture S.Lott · Jun 4, 2009

Your code is almost correct.

See __import__ function.

def doSomething(name):
    name = "package." + name
    mod = __import__(name, fromlist=[''])
    mod.doSomething()