Next / Previous / Contents / TCC Help System / NM Tech 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)
4.0
>>> pi
3.1415926535897931

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)
5.0
>>> math.pi
3.1415926535897931

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)
5.0
>>> crunch.pi
3.1415926535897931