The built-in function __import__() is called by the import statement. Import statement is the most common way of invoking the import machinery. It is a rarely used method and it helps to import modules in runtime also.
__import__(name, globals=None, locals=None, fromlist=(), level=0) #where name indicates the name of the import module
Takes five parameters. This function can change the semantics of the import statement as the statement calls this function.
Parameter | Description | Required / Optional |
---|---|---|
name | the name of the module you want to import | Required |
globals and locals | Determines how to interpret the name in a package context. Default is none. | Optional |
fromlist | objects or submodules that should be imported by name | Optional |
level | specifies whether to use absolute or relative imports. Default is 0 | Optional |
In the case of import a module by name, we can use importlib.import_module(). If the named module cannot be found, will arise a ModuleNotFoundError.
Input | Return Value |
---|---|
If parameters | import object |
maths = __import__('math', globals(), locals(), [], 0)
print(maths.fabs(-3.5))
Output:
3.5
rand = __import__('random')
print(rand.randint(0,10))
print(rand.randint(0,10))
Output:
6 2