The __import__() function is an advanced function used to dynamically import modules. The import statement essentially calls this function.

Function Syntax

__import__(name, globals=None, locals=None, fromlist=[], level=0)

Parameters:

  • name: The name of the module to import, as a string.
  • globals: The global namespace.
  • locals: The local namespace.
  • fromlist: Specifies a list of names to import from the module.
  • level: The level for relative imports.

The __import__() function returns the imported module object.

Examples of the __import__() Function

Simple import method:

# Equivalent to import math
math = __import__('math')

print(math.sqrt(4)) # 2.0
print(math.pi)      # 3.141592653589793

When importing a custom .py file, do not include .py in the name:

# Import example.py
example = __import__('example')

A module is loaded only once:

import math

math_module = __import__('math')

print(math is math_module)  # True

The role of the fromlist parameter:

# Without fromlist, always returns the top-level module
result = __import__('os.path')
print(result.__name__)  # os
# result is the os module
#print(result.join('a','b')) # Error
print(result.path.join('a','b'))

# With fromlist → returns the module specified in the import statement
# The content in fromlist can be arbitrary but must be a non-empty list
result = __import__('os.path', fromlist=['fake'])
print(result.__name__)  # ntpath
# result is os.path
#print(result.path.join('a','b')) # Error
print(result.join('a','b'))