Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python __import__() function: import module name

The __import__() function in Python is a built-in function used to dynamically import modules at runtime. Although the import statement is the preferred way to import modules, __import__() can be useful in certain situations where you need to import a module based on a variable or string. In this tutorial, we will cover the basics of the __import__() function, its usage, and some examples.

Syntax:

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

Parameters:

  • name: The name of the module you want to import. This is a required parameter.
  • globals: An optional dictionary representing the global namespace. It is usually not needed and can be left as None.
  • locals: An optional dictionary representing the local namespace. It is usually not needed and can be left as None.
  • fromlist: An optional list of objects to be imported from the module. An empty tuple () can be used if you don't want to import specific objects.
  • level: An optional integer that specifies the relative level of the import. 0 means absolute import, and positive numbers mean relative imports.

Example 1: Basic usage of __import__()

# Importing the 'math' module using __import__()
module_name = 'math'
math_module = __import__(module_name)

# Accessing the 'sqrt' function from the 'math' module
sqrt = math_module.sqrt

print("Square root of 9 is", sqrt(9))  # Output: Square root of 9 is 3.0

Example 2: Importing specific objects from a module

# Importing the 'randint' function from the 'random' module using __import__()
module_name = 'random'
function_name = 'randint'
random_module = __import__(module_name, fromlist=[function_name])

randint = random_module.randint

print("Random integer between 1 and 10:", randint(1, 10))

Example 3: Relative imports using __import__()

Suppose we have the following package structure:

my_package/
������ __init__.py
������ module_a.py
������ module_b.py

In module_a.py, we want to import a function my_function from module_b.py. We can use __import__() to achieve this:

# In module_a.py
module_b = __import__("module_b", fromlist=["my_function"], level=1)
my_function = module_b.my_function

Keep in mind that using __import__() is not the recommended way to import modules, as it can be harder to read and maintain than using the import statement. However, it can be useful in situations where you need to dynamically import modules based on a variable or a string.

  1. Dynamic module import using import() in Python:

    • Description: The import() function allows dynamic module imports based on runtime conditions. It returns the imported module or object.
    • Code:
      module_name = "math"
      math_module = importlib.import_module(module_name)
      result = math_module.sqrt(25)
      print(result)
      
  2. Importing modules with variable names using import():

    • Description: Use a variable to hold the module name and then dynamically import the module using import().
    • Code:
      module_name = "math"
      math_module = importlib.import_module(module_name)
      result = math_module.sqrt(25)
      print(result)
      
  3. Dynamic module loading and unloading with import() in Python:

    • Description: Dynamic module loading and unloading can be achieved by using importlib.reload() to reload a module dynamically.
    • Code:
      import importlib
      
      module_name = "my_module"
      my_module = importlib.import_module(module_name)
      
      # ... some changes in my_module source code ...
      
      my_module = importlib.reload(my_module)
      
  4. Using import() for conditional imports in Python:

    • Description: import() is handy when you want to conditionally import a module based on some runtime conditions.
    • Code:
      if some_condition:
          module_name = "math"
          math_module = importlib.import_module(module_name)
          result = math_module.sqrt(25)
          print(result)