To use any package in your code, you must first make it available. You have to import it. You cannot use anything in Python until it is defined. Some things are built in, for example basic types (like int, float, etc.) can be used anytime.
But most of the things you want to do will take a little more than that. For example, if you want to calculate the cosine of 1 radian, if you run math.cos (0), you will get a NameError since the math is undefined.
You must tell python to first import this module into your code so you can use it.
""" math.cos (0) Traceback (most recent call last): File ""stdin"", line 1, in "module" NameError: name ’math’ is not defined""" import math""" math.cos (0) 1.0
To dynamically import Python modules, you can use the import_module (moduleName) function of the importlib package. You must have moduleName as a string. For example,
""" from importlib import import_module""" moduleName = "os"""" globals () [moduleName] = import_module (moduleName)
If you want to import a list of modules dynamically, you can even call this from within a for loop. For example,
""" import importlib""" modnames = ["os", "sys", "math"]""" for lib in modnames: ... globals () [lib] = importlib.import_module (lib)
Calling globals () returns a dict. We can set the lib key for each library as an object returned to us when the module is imported.