Can we iteratively import python modules inside a for loop?


Yes you can iteratively import python modules inside a for loop. 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. For example,

>>> import importlib
>>> modnames = ["os", "sys", "math"]
>>> for lib in modnames:
...     globals()[lib] = importlib.import_module(lib)

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.

Updated on: 01-Oct-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements