Dealing With Modules Part 2
Using the import statement
The import statement is
the most common method for importing a module into Python. This approach is
fast and ensures that the entire module is ready for use. The following steps
get you started using the import statement.
Open the Python Shell.
You see the Python Shell
window appear.
Change directories to the downloadable source
code directory.
See the instructions
found in the “Changing the current Python directory” sidebar.
Type import MyLibrary and press Enter.
Python imports the
contents of the MyLibrary.py file that you created in the “Creating Code
Groupings” section of the Post. The entire library is now ready for use.
It’s important to know
that Python also creates a cache of the module in the __pycache__ subdirectory.
If you look into your source code directory after you import MyLibrary for the
first time, you see the new __pycache__ directory. If you want to make changes
to your module, you must delete this directory. Otherwise, Python will continue
to use the unchanged cache file instead of your updated source code file.
Type dir(MyLibrary) and press Enter.
You see a listing of the
module contents, which includes the SayHello() and SayGoodbye() functions, as
shown in .
Type MyLibrary.SayHello(“Josh”) and press
Enter.
The SayHello() function
outputs the expected text,
Notice that you must
precede the attribute name, which is the Say Hello() function in this case,
with the module name, which is MyLibrary. The two elements are separated by a
period. Every call to a module that you import follows the same pattern.
Type MyLibrary.SayGoodbye(“Sally”) and press
Enter. The SayGoodbye( ) function outputs the expected text.
Close the Python Shell.
The Python Shell window
closes.
Using the from...import statement
The from...import
statement has the advantage of importing only the attributes you need from a
module. This difference means that the module uses less memory and other system
resources than using the import statement does. In addition, the from...import
statement makes the module a little easier to use because some commands, such
as dir(), show less information, or only the information that you actually
need. The point is that you get only what you want and not anything else. The
following steps dem-onstrate using the from...import statement.
Open the Python Shell.
You see the Python Shell
window appear.
Change directories to the downloadable source
code directory.
See the instructions
found in the “Changing the current Python direc-tory” sidebar.
Type from MyLibrary import SayHello and press
Enter.
Python imports the
SayHello() function that you create in the “Creating Code Groupings” section,
earlier in the Post. Only this specific function is now ready for use.
You can still import the
entire module, should you want to do so. The two techniques for accomplishing
the task are to create a list of mod-ules to import (the names can be separated
by commas, such as from
MyLibrary import
SayHello, SayGoodbye) or to use the asterisk
(*) in place of a
specific attribute name. The asterisk acts as a wildcard character that imports
everything.
Type dir(MyLibrary) and press Enter.
Python displays an error
message, . Python imports only the attributes that you specifically request.
This means that the MyLibrary module isn’t in memory — only the attributes that
you requested are in memory.
Type dir(SayHello) and press Enter.
You see a listing of
attributes that are associated with the SayHello() function. It isn’t important
to know how these attributes work just now, but you’ll use some of them later
in the book.
Type SayHello(“Angie”) and press Enter.
The SayHello() function
outputs the expected text
When you import
attributes using the from...import statement, you don’t need to precede the
attribute name with a module name. This fea-ture makes the attribute easier to
access.
Using the from...import
statement can also cause problems. If two attributes have the same name, you
can import only one of them. The import statement prevents name collisions,
which is important when you have a large number of attributes to import. In
sum, you must exer-cise care when using the from...import statement.
Type SayGoodbye(“Harold”) and press Enter.
You imported only the
SayHello() function, so Python knows noth-ing about SayGoodbye() and displays
an error message. The selective nature of the from...import statement can cause
problems when you assume that an attribute is present when it really isn’t.
Close the Python Shell.
The Python Shell window
closes.
Finding Modules on Disk
In order to use the code
in a module, Python must be able to locate the module and load it into memory.
The location information is stored as paths within Python. Whenever you request
that Python import a module, Python looks at all the files in its list of paths
to find it. The path information comes from three sources:
Environment variables: Post 3 tells you about
Python environment variables, such as PYTHONPATH, that tell Python where to
find modules on disk.
Current directory: Earlier in this Post, you
discover that you can change the current Python directory so that it can locate
any modules used by your application.
Default directories: Even when you don’t
define any environment variables and the current directory doesn’t yield any
usable modules, Python can still find its own libraries in the set of default
directories that are included as part of its own path information.
It’s helpful to know the
current path information because the lack of a path can cause your application
to fail. The following steps demonstrate how you can obtain path information:
Open the Python Shell.
You see the Python Shell
window appear.
Type import sys and press Enter.
Type for p in sys.path: and press Enter.
Python automatically
indents the next line for you. The sys.path attribute always contains a
listing of default paths.
Type print(p) and press Enter twice.
You see a listing of the
path information. Your listing may be different depending on your platform, the
version of Python you have installed, and the Python features you have
installed.
The sys.path attribute
is reliable but may not always contain every path that Python can see. If you
don’t see a needed path, you can always check in another place that Python
looks for information. The following steps show how to perform this task:
Type import os and press Enter.
Type
os.environ[‘PYTHONPATH’].split(os.pathsep) and press Enter.
When you have a
PYTHONPATH environment variable defined, you see a list of paths. However, if
you don’t have the environment variable defined, you see an error message
instead.
Notice that both the
sys.path and the os.environ['PYTHONPATH'] attributes contain the
C:\BP4D\Newfolder entry in this case.
The sys.path attribute
doesn’t include the split() function,
which is why the example
uses a for loop with it. However, the os. environ['PYTHONPATH'] attribute does
include the split() func-tion, so you can use it to create a list of individual
paths.
You must provide split()
with a value to look for in splitting a list of items. The os.pathsep constant
(a variable that has one, unchangeable, defined value) defines the path
separator for the current platform so that you can use the same code on any
platform that supports Python.
Close the Python Shell.
The Python Shell window
closes.
You can also add and
remove items from sys.path. For example, if you want to add POST to the list of
modules, you type sys.path.append("C:\\ BP4D\\Post09") and press
Enter in the Python Shell window. When you list the sys.path contents again,
you see that the new entry is added. Likewise, when you want to remove an
entry, such as Post 9, you type sys.path.remove("C:\\BP4D\\Post09")
and press Enter.
0 comments:
Post a Comment