
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iteratively Import Python Modules Inside a For Loop
What is a Python Module?
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. Also, Python comes with built-in modules, which include os and math.
Usually, modules are imported statically at the top of the code, but there can also be cases that require dynamic importing. Some of the reasons might be ?
- You are not sure which module to import until the program runs.
- You are building plugin systems(a software program that allows users/developers to extend functionality by adding extra modules).
- You want to import modules based on user input.
Importing Python Modules Iteratively
Yes, you can iteratively import Python modules inside a for loop. For this, you need to have a list of modules you want to import as strings. You can use the inbuilt importlib.import_module(module_name) to import the modules.
The for loop in Python iterates over a sequence, executing a block of code for each item in the sequence.
The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module.
The example below uses for loop for dynamically importing multiple modules. This helps to avoid repetitive import statements and allows to iterate over a list of module names and import them one by one.
import importlib #List of modules to import modnames = ["os", "sys", "math"] #Importing modules dynamically inside for loop for lib in modnames: globals()[lib]=importlib.import_module(lib) #Use the modules print("OS Name:", os.name) print("Python Version:", sys.version) print("Square Root of 81:", math.sqrt(81))
The code above returns where the Python code is running, the exact Python version, and the square root. Following is the output of the code -
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 that the Python code is running on macOS or Linux. The next line confirms the exact Python version (here, 3.12.3). And lastly, though the answer for the square root is 9, the math.sqrt() function returns 9.0 as it returns float, not an integer.