Python Language Programmatic importing


Example

Python 2.x2.7

To import a module through a function call, use the importlib module (included in Python starting in version 2.7):

import importlib
random = importlib.import_module("random")

The importlib.import_module() function will also import the submodule of a package directly:

collections_abc = importlib.import_module("collections.abc")

For older versions of Python, use the imp module.

Python 2.x2.7

Use the functions imp.find_module and imp.load_module to perform a programmatic import.

Taken from standard library documentation

import imp, sys
def import_module(name):
    fp, pathname, description = imp.find_module(name)
    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        if fp:
            fp.close()

Do NOT use __import__() to programmatically import modules! There are subtle details involving sys.modules, the fromlist argument, etc. that are easy to overlook which importlib.import_module() handles for you.