Python __import__() Method

The __import__() method is called by the import statement. This method can change the semantics of the import statement, which is strongly discouraged.

__import__() Syntax:

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

Parameters:

  1. name: The name of module to import.
  2. gloabals: (Optional) Determines how to interpret name in a package context. Default is none.
  3. locals: (Optional) Determines how to interpret name in a package context. Default is none.
  4. fromlist: (Optional) names of objects or submodules to be imported from module.
  5. level: (Optional) Specifies wether to use absolute or relative imports. Default is 0.

Return type:

Returns an import object

The following example imports the math module.

Example: __import__()
rnd = __import__('random')

print(rnd.randint(0,10))
print(rnd.randint(0,10))
Output
6
2

Note that Direct use of __import__() is discouraged in favor of importlib.import_module().

Want to check how much you know Python?