The __import__()
function is a part of the Python's import system. It is used to dynamically load modules into the program.
__import__(name, globals, locals, fromlist)
name
(required): The name of the module to import, provided as a string.globals
(optional): A dictionary representing the global namespace. If not specified, the current global namespace is used.locals
(optional): A dictionary representing the local namespace. If not specified, the current local namespace is used.fromlist
(optional): Specifies the objects to be imported from the module. If not specified, it imports the top-level module itself.
m = __import__('math')
print(m.pi)
print(m.pow(5, 2))
m= __import__('math', fromlist = ['pi', 'e'])
print(m.pi)
print(m.e)
s= __import__('string', fromlist = ['ascii_lowercase', 'ascii_uppercase'])
print(s.ascii_lowercase)
print(s.ascii_uppercase)
Please note that the __import__
function is implemented with double underscores. Normally, functions or methods implemented this way are not meant to be used directly or unnecessarily and doing so should generally be avoided .
The __import__
function is meant to be used by the Python interpreter when executing a module's import statement. It can be used directly, but only in certain cases where the standard import statement cannot be used. These include dynamically loading modules, and using it as part of an import hook to modify the behavior of the normal import process. It is, therefore, generally recommended that you use the import
statement for static imports whenever possible.
import math
print(math.e)
print(math.pi)
import math as _math
print(_math.pi)
print(_math.e)
from math import e, pi
print(e)
print(pi)