How I can dynamically import Python module?

PythonServer Side ProgrammingProgramming

To dynamically import Python modules, you can use the importlib package's import_module(moduleName) function. You need to have moduleName as a string. For example,

>>> from importlib import import_module
>>> moduleName = "os"
>>> globals()[moduleName] = import_module(moduleName)

If you want to dynamically import a list of modules, you can even call this from a for loop. 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 10:53:17
Advertisements