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.

Your Python installation will come with a large collection of released modules.

You can also create your own modules. Just place Python statements defining variables, functions, and classes into a file whose name ends in “

`.py`

”.

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

The

`from`

statement copies items from a module into your namespace. After importing an item in this way, you can refer to the item simply by its name.General forms:

from

import * from`moduleName`

import`moduleName`

,`name`

_{1}, ...`name`

_{2}The first form imports all the items from the module named

. If you want to import only specific items, use the second form, and enumerate the names you want from that module.`moduleName`

The

`import`

statement makes an entire module's content available to you as a separate namespace. To refer to some item named

in a module named`N`

, use the dot notation,`M`

..`M`

`N`

Here is the general form:

import

, ...`moduleName`

If you want to use some module

in this way, but you want to change the name to some different name`M`

, use this form:`A`

import

as`M`

`A`

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