Next / Previous / Contents / Shipman's homepage

22.6. The import statement: Use a module

One of the cornerstones of Python's design philosophy is to keep the language relatively small and well-defined, and move all non-essential functionality to library modules. The import and from statements allow your programs to use items from these library modules.

There are two different statements you can use to import items from a module:

Here are some examples that use the standard math module that is always available in a proper Python install. This module has functions such as sqrt() (square root), as well as variables such as pi. (Although π is a constant in the mathematical sense, the name pi is a variable in the Python sense.)

>>> from math import *
>>> sqrt(16)
>>> pi

If you wanted only the sqrt function and the variable pi, this statement would do the job:

from math import sqrt, pi

Now some examples of the second form.

>>> import math
>>> math.sqrt(25)
>>> math.pi

Suppose your program already used the name math for something else, but you still want to use functions from the math module. You can import it under a different name like this:

>>> import math as crunch
>>> crunch.sqrt(25)
>>> crunch.pi