Python – Dynamic loading of python modules


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)

How do I do this?

Best Solution

Your code is almost correct.

See __import__ function.

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