Python __import__() Function



The Python __import__() function is a built-in function used to import a module during runtime. It should be noted that the use of this function is often discouraged as it can change the semantics of the import statement.

In our Python program, we need various functions and classes from other modules. Though we can also import named modules at the beginning of the code, but sometimes, we may need the module temporarily for only few lines of code. In this situation, we use __import__() function.

Syntax

Following is the syntax of the Python __import__() function −

__import__(name, globals, locals, fromlist, level)

Parameters

The Python __import__() function accepts the following parameters −

  • name − It represents the name of the module we want to import in our program.

  • globals − It specify how to interpret the specified module.

  • locals − It also specify how to interpret the imported module.

  • fromlist − This parameter specifies objects or submodules that we want to import as a list.

  • level − The level 0 represents absolute and a positive number represent the relative level.

Return Value

The Python __import__() function returns the object or module that we specify.

Examples

In this section, we will see some examples of __import__() function −

Example 1

The following example shows the basic usage of Python __import__() function. Here, we are importing a module named "math" into our program.

#importing the module
importingModule = __import__("math")
# using sqrt method from the module
print(importingModule.sqrt(49))

When we run above program, it produces following result −

7.0

Example 2

We can also select a specific method from a given module to import into our program. In the code below, we are importing only "sqrt" method from Math module.

#importing only sqrt method from Math module
importingSqrt = getattr(__import__("math"), "sqrt")
print("The square root of given number:")
print(importingSqrt(121))

Following is an output of the above code −

The square root of given number:
11.0

Example 3

The code below demonstrates how to import the numpy module by giving an alias to it.

#importing only numpy module
np = __import__('numpy', globals(), locals(), [], 0)
print("The newly created array:")
print(np.array([22, 24, 26, 28, 30, 32]))

Output of the above code is as follows −

The newly created array:
[22 24 26 28 30 32]
python_built_in_functions.htm
Advertisements