While writing a code, there might be a need for some specific modules. So we import those modules by using a single-line code in Python. But what if the name of the module needed is known to us only during runtime? How can we import that module? One can use Python’s inbuilt __import__() function. It helps to import modules in runtime also.
Syntax of __import__() in Python
The Python __import__() function had the following syntax:
Syntax: __import__(name, globals, locals, fromlist, level)
Parameters:
- name: Name of the module to be imported
- globals and locals: Interpret names
- formlist: Objects or submodules to be imported (as a list)
- level: Specifies whether to use absolute or relative imports. The default is -1(absolute and relative).
Exceptions of __import__ function in Python
The Python __import__() method is a built-in method that is used to import modules and functions. It imports the modules while executing the code. It is not widely used as it can change the semantics of the import statement.
How to use __ import __() in Python?
The __import__() module is used to dynamically import a module in the code. We just need to specify the name of the module as a string to the __import__() method. It will then return the object of the imported module, which can be used to access the function and classes of the module.
Example of __ import __() function in Python
Let us see a few examples to implement the __import__() function in Python to better understand its working.
Example 1: In this example, we will use the __import__() function to import the Python NumPy module dynamically to create an array.
Python3
# importing numpy module # it is equivalent to "import numpy as np" np = __import__ ( 'numpy' , globals (), locals (), [], 0 ) # array from numpy a = np.array([ 1 , 2 , 3 ]) # prints the type print ( type (a)) |
Output:
<class 'numpy.ndarray'>
Example 2: In this example, we are importing the Numpy module as well as its complex() and array() functions using the __import__() function.
Python3
# from numpy import complex as comp, array as arr np = __import__ ( 'numpy' , globals (), locals (), [ 'complex' , 'array' ], 0 ) comp = np. complex arr = np.array comp_number = comp( 5 , 2 ) my_arr = arr([ 1 , 2 , 3 , 4 ]) # prints the type print (comp_number) print (my_arr) |
Output:
(5+2j)
[1 2 3 4]
Application
__import__() in Python
is not really necessary in everyday Python programming. Its direct use is rare. But sometimes, when there is a need of importing modules during the runtime, this function comes in quite handy.