Can we iteratively import python modules inside a for loop?

A module in Python is a simple .py file that contains code, which includes functions, classes, and variables. The module can be reused in other programs. Python also comes with built-in modules like os and math.

Usually, modules are imported statically at the top of the code, but there are cases that require dynamic importing ?

  • You are not sure which module to import until the program runs.
  • You are building plugin systems that allow users to extend functionality by adding modules.
  • You want to import modules based on user input or configuration.

Importing Python Modules Iteratively

Yes, you can iteratively import Python modules inside a for loop. This is done using importlib.import_module() function along with a list of module names as strings.

Basic Example

Here's how to dynamically import multiple modules using a for loop ?

import importlib

# List of modules to import
module_names = ["os", "sys", "math"]

# Importing modules dynamically inside for loop
for lib in module_names:
    globals()[lib] = importlib.import_module(lib)

# Use the imported modules
print("OS Name:", os.name)
print("Python Version:", sys.version)
print("Square Root of 81:", math.sqrt(81))
OS Name: posix
Python Version: 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0]
Square Root of 81: 9.0

Here, posix indicates the Python code is running on macOS or Linux. The globals()[lib] call adds each imported module to the global namespace, making them accessible as if they were imported normally.

How It Works

The process involves three key components ?

  • importlib.import_module() − Imports a module by its string name
  • globals() − Returns a dictionary of the global namespace
  • for loop − Iterates through the list of module names

Alternative Approach with Dictionary Storage

Instead of adding to globals, you can store modules in a dictionary ?

import importlib

# List of modules to import
module_names = ["datetime", "random", "json"]

# Dictionary to store imported modules
modules = {}

# Import modules and store in dictionary
for name in module_names:
    modules[name] = importlib.import_module(name)

# Use the modules
print("Current date:", modules['datetime'].datetime.now().date())
print("Random number:", modules['random'].randint(1, 100))
print("JSON dumps:", modules['json'].dumps({"key": "value"}))
Current date: 2024-12-19
Random number: 42
JSON dumps: {"key": "value"}

Common Use Cases

  • Plugin systems − Load plugins dynamically based on configuration
  • Conditional imports − Import modules based on runtime conditions
  • Configuration-driven imports − Load modules specified in config files
  • Testing frameworks − Import test modules dynamically

Conclusion

Yes, you can iteratively import Python modules inside a for loop using importlib.import_module(). This approach is useful for dynamic module loading, plugin systems, and configuration-driven applications where module requirements are determined at runtime.

Updated on: 2026-03-24T17:07:37+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements