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 in import math.

>>> import math
>>> math.pi
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 add our own location to this list as well.

No comments:

Post a Comment