Usage of __import()__ Method in Python

In this article, we will learn about the usage of __import()__ Method in Python. Generally, this method is invoked by the Import statement. The Import module is used to provide accessibility to a user to use Modules in Python. It is a function that is not needed in daily Python programming. Using this method is not recommended due to the long and complex syntax. So, let’s have a look at the usage of the __import()__ Method in Python.

__import()__ Method:

This method is used to invoke the import statement. but nowadays we don’t use it because we can directly use the import statement in our daily programming. Use of __import()__ method is used in rare cases such as when you want to Import-Module only known at the run time of the program.

Syntax of __import()__ method is:

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

Parameters:

  • Name:
    Name of the module we have to import.
  • Globals:
    It is optional. It is used to determine how to interpret.
  • Locals:
    It is optional. It is used to specify how to interpret the name of the context of a package. The locals don’t use locally, we should use globally.
  • Fromlist:
    It is optional. Formlist had data about which sub-modules that should like to import from the module specified in the method.
  • Level:
    ┬áIt is optional. It represents both relative and absolute imports. By default, the value is -1 that shows that both ‘absolute’ and ‘relative’ imports can be used.

Let’s some see some examples on __import()__ method using Python:

For Example:

ma=__import__('math',globals(),locals(),[],0)
print(ma.fabs(-2.3))

Consequently, the result is:

2.3

For Example:

n=__import__('numpy',globals(),locals(),[],0)
a=n.array([1,3])
print(type(a))

Consequently, the result is:

<class 'numpy.ndarray>

It is not necessary to use this method in daily Python programming. Its direct use is rare, But sometimes, when the import module at run time, this method is very useful.

Leave a Reply

Your email address will not be published. Required fields are marked *