Change language

Python import statement with examples

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.



Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method