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.

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.

Similar Reads

Syntax of __import__() in Python

The Python __import__() function had the following syntax:...

Example of __ import __() function in Python

Let us see a few examples to implement the __import__() function in Python to better understand its working....

Contact Us