Summary of several ways to import modules in Python

  • 2020-05-30 20:32:32
  • OfStack

Many useful functions are encapsulated inside the module, and sometimes need to be imported when invoked outside the module. The common ways are as follows:

1 . import


>>> import sys
>>> sys.path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

Most commonly, the name of the module to be imported is written down later.

2 .from .. import ..

Similar to import, but more specific to import methods or variables, such as:


>>> from sys import path
>>> path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

However, it can cause namespace pollution and import is recommended.

3. Import the module with a name string

We might want to import the module like this:


 >>> import "sys"
SyntaxError: invalid syntax

python import accepts a variable instead of a string. How about assigning "sys" to a variable?


>>> x="sys"
>>> import x
Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
  import x
ImportError: No module named 'x'

This does not work either; this means importing a module named x instead of the sys module represented by x.

We need to use the exec function:


>>> x="sys"
>>> exec("import "+ x)
>>> sys.path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

Build the import statement into a string and pass it to the exec function for execution.

The disadvantage of exec is that it compiles every time it executes, and running it multiple times can affect performance.

A better way is to use the function s 45en__.


>>> x="sys"
>>> sys = __import__(x)
>>> sys.path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

This approach requires a variable to hold the module object for subsequent calls.


Related articles: