Programmatic importing

suggest change

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.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Importing modules:
* Programmatic importing

Table Of Contents
2 Filter
3 List
7 Loops
10 Importing modules
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve