Python | __import __ () function

NumPy | Python Methods and Functions

But what if the name of the required module is known to us only at runtime? How can we import this module? You can use the built-in __import__() function __import__() . It also helps to import modules at runtime.

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. Default is -1 (absolute and relative).

Example # 1 :

# import numpy module
# this is equivalent to & quot; import numpy & quot;

np = __ import__ ( ` numpy` , globals (), locals (), [], 0 )

 
# numpy array

a = np.array ([ 1 , 2 , 3 ])

 
# prints the type

print ( type (a))

Exit :

 & lt; class `numpy.ndarray` & gt; 

Example # 2 :
Both of the following statements have the same meaning and do the same job.

# from numpy import complex as comp, array as arr

np = __ import__ ( `numpy` , globals < / code> (), locals (), [ `complex` , ` array` ], 0 )

 

comp = np. complex

arr = np.array

Application :
__import__() is not really required in day to day Python programming. Its direct use is rare. But sometimes, when you need to import modules at runtime, this feature is quite useful.





Get Solution for free from DataCamp guru