Importing Modules

When you want to refer to someone else's work in a scientific paper, you have to cite it in your bibliography. When you want to use a function from a module, you have to import it. To tell Python that you want to use functions in the math module, for example, you use this import statement:

Download modules/import.cmd

Once you have imported a module, you can use the built-in help function to see what it contains:1

Download modules/help_math.cmd

Help on built-in module math: NAME



(built-in) DESCRIPTION

This module is always available. It provides access to the mathematical functions defined by the C standard.


Return the arc cosine (measured in radians) of x.

Return the arc sine (measured in radians) of x.

Great—our program can now use all the standard mathematical functions. When we try to calculate a square root, though, we get an error telling us that Python is still unable to find the function sqrt:

Download modules/sqrt.cmd

Traceback (most recent call last):

File "<string>", line 1, in <string> NameError: name 'sqrt' is not defined

The solution is to tell Python explicitly to look for the function in the math module by combining the module's name with the function's name using a dot:

Download modules/sqrt2.cmd

1. When you do this interactively, Python displays only a screenful of information at a time. Press the spacebar when you see the "More" prompt to go to the next page.

Figure 4.1: How import works

The reason we have to join the function's name with the module's name is that several modules might contain functions with the same name. For example, does the following call to floor refer to the function from the math module that rounds a number down or the function from the (completely fictional) building module that calculates a price given an area (see Figure 4.1)?

Download modules/import_ambiguity.cmd

>>> import math >>> import building >>> floor(22.7)

once a module has been imported, it stays in memory until the program ends. There are ways to "unimport" a module (in other words, to erase it from memory) or to reimport a module that has changed while the program is running, but they are rarely used. In practice, it's almost always simpler to stop the program and restart it.

Modules can contain more than just functions. The math module, for example, also defines some variables like pi. Once the module has been imported, you can use these variables like any others:

Download modules/pi.cmd

>>> math.pi 3.1415926535897931 >>> radius = 5

>>> print 'area is %6f' % (math.pi * radius ** 2) area is 78.539816

You can even assign to variables imported from modules:

Download modules/pi_change.cmd

>>> math.pi = 3 # would turn circles into hexagons >>> radius = 5

>>> print 'circumference is', 2 * math.pi * radius circumference is 30

Don't do this! Changing the value of n is not a good idea. In fact, it's such a bad idea that many languages allow programmers to define unchangeable constants as well as variables. As the name suggests, the value of a constant cannot be changed after it has been defined: n is always 3.14159 and a little bit, while SECONDS_PER_DAY is always 86,400. The fact that Python doesn't allow programmers to "freeze" values like this is one of the language's few significant flaws.

Combining the module's name with the names of the things it contains is safe, but it isn't always convenient. For this reason, Python lets you specify exactly what you want to import from a module, like this:

Download modules/from.cmd

>>> print 'circumference is %6f' % (2 * pi * radius) circumference is 31.415927

This can lead to problems when different modules provide functions that have the same name. If you import a function called spell from a module called magic and then you import another function called spell from the module grammar, the second replaces the first. It's exactly like assigning one value to a variable, then another: the most recent assignment or import wins.

This is why it's usually not a good idea to use import *, which brings in everything from the module at once. It saves some typing:

Download modules/from2.cmd

>>> from math import * >>> '%6f' % sqrt(8) '2.828427'

but using it means that every time you add anything to a module, you run the risk of breaking every program that uses it.

The standard Python library contains several hundred modules to do everything from figuring out what day of the week it is to fetching data from a website. The full list is online at html; although it's far too much to absorb in one sitting (or even one course), knowing how to use the library well is one of the things that distinguishes good programmers from poor ones.

Was this article helpful?

0 0

Post a comment