Sunday, June 7, 2020

Python Import

When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this.
For example, we can import the math module by typing the following line:
import math
We can use the module in the following ways:
import math
print(math.pi)
Output
3.141592653589793
Now all the definitions inside math module are available in our scope. We can also import some specific attributes and functions only, using the from keyword. For example:
>>> from math import pi
>>> pi
3.141592653589793
While importing a module, Python looks at several places defined in sys.path. It is a list of directory locations.
>>> import sys
>>> sys.path
['', 
 'C:\\Python33\\Lib\\idlelib', 
 'C:\\Windows\\system32\\python33.zip', 
 'C:\\Python33\\DLLs', 
 'C:\\Python33\\lib', 
 'C:\\Python33', 
 'C:\\Python33\\lib\\site-packages']
We can also add our own location to this list.

No comments:

Post a Comment