Open In App

Python | __import__() function

Last Updated : 14 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Previous Article
Next Article

Similar Reads

Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples. What is Calling a Function
4 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
3 min read
Accessing Python Function Variable Outside the Function
In Python, variables defined within a function have local scope by default. But to Access function variables outside the function usually requires the use of the global keyword, but can we do it without using Global. In this article, we will see how to access a function variable outside the function without using "Global". Accessing Function Variab
3 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Article Tags :
Practice Tags :