Python import statement with examples

Python Methods and Functions

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.



< / ins>


 & gt; & gt; & gt; math.cos (0) Traceback (most recent call last): File "& lt; stdin & gt;", line 1, in & lt; module & gt; NameError: name 'math' is not defined & gt; & gt; & gt; import math & gt; & gt; & gt; 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,

 & gt; & gt; & gt; from importlib import import_module & gt; & gt; & gt; moduleName = "os" & gt; & gt; & gt; 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,

 & gt; & gt; & gt; import importlib & gt; & gt; & gt; modnames = ["os", "sys", "math"] & gt; & gt; & gt; 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.







Tutorials