Can we iteratively import python modules inside a for loop?

PythonServer Side ProgrammingProgramming

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.

raja
Published on 20-Dec-2017 11:13:56
Advertisements