How to do multiple imports in Python?



To import multiple modules, just use the import statement multiple times. For example,

>>> import os
>>> import math
>>> import sys

Sometimes grouping imports make more sense. 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)

Advertisements