What is __import__() function in Python?

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.

In Python, the __import__() function is a built-in function that allows dynamic importing of modules at runtime. It can be used to import modules by name as strings, and can also be used to import modules from a package.

The syntax of the __import__() function is as follows: 

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

Here, name is the name of the module to be imported, globals and locals are optional dictionaries that specify the global and local namespace, respectively. fromlist is a list of names of objects to be imported from the module, and level specifies the level in the package hierarchy where the module is located.

For example, the following code demonstrates how to use __import__() to dynamically import a module: 

import_module = __import__('module_name')

This code imports the module named module_name and assigns it to the variable import_module.

Note that __import__() is not commonly used in everyday Python programming, as it can make code harder to read and understand. Instead, the import statement is generally preferred, as it provides a clearer and more explicit way of importing modules. However, __import__() can be useful in certain situations, such as when modules need to be imported dynamically based on user input or other runtime conditions.

Submit Your Programming Assignment Details