How to use multiple modules with Python import Statement?

PythonServer Side ProgrammingProgramming

To import multiple modules with a single import statement, just separate the module names by commas. For example,

>>> import math, sys, os

If you want to change the name under which the modules are imported, just add as after each module name followed by module alias. For example,

>>> import math as Mathematics, sys as system

If you have a list of modules you want to import as strings, then you can use the inbuilt __import__(module_name). For example,

>>> modnames = ["os", "sys", "math"]
>>> for lib in modnames:
 ...     globals()[lib] = __import__(lib)
Published on 19-Dec-2017 16:14:13