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.
Python | __import__() function
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.
Contact Us