Datasheet

Chapter 1: A Python Primer
13
3. You can import specific names only within a module, without importing the whole module, by
using the
from < module > import < name > statement. This can be useful for performance
reasons if you only need one function from a large module.
4. If a module has a name that s difficult to work with or remember, and you want to use a name
to represent it that is meaningful to you, simply use the
as keyword and import < module > as
< identifier >
.
Reload
Reload is another very useful command, especially when entering code within the Python interactive
interpreter. It enables you to reload a particular module without reloading Python. For example, if you
wanted to reload the
os module, you would simply enter reload os .
If you re wondering why you would ever want to do that, one scenario would be if you have a Python
script that runs all the time and it accesses a module on another machine. Assuming you always want to
ensure that you re running the most current version of the remote module you re accessing, you ’ d use
the
reload command.
How Python Finds Modules to Load
When you use an import statement, you don t tell Python where the module that needs to be loaded
is located. How, then, does it know where to find the file? The answer to that question is the module
search path .
The Module Search Path
Python has a predefined priority specifying where it should look for modules, known as the module
search path. When you enter an
import command and the name of the module, Python checks the
following locations in the order shown here:
1. The home directory This is either the directory from which you launched the Python
interactive interpreter or the directory where the main Python program is located.
2. PYTHONPATH This is an environment variable set in the system. Its value is a list of
directories, which Python will search for modules.
3. Standard library directories The directory in which the standard libraries are located are
searched next.
c01.indd 13c01.indd 13 6/2/08 12:03:11 PM6/2/08 12:03:11 PM