04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

210 CHAPTER 10 ■ BATTERIES INCLUDED<br />

Naming Your Module<br />

As you may have noticed, the file that contains the code of a module must be given the same<br />

name as the module—with an additional .py file name extension. In Windows, you can use the<br />

file name extension .pyw instead. You learn more about what that file name extension means<br />

in Chapter 12.<br />

Packages<br />

To structure your modules, you can group them into packages. A package is basically just another<br />

type of module. The interesting thing about them is that they can contain other modules. While<br />

a module is stored in a file (with the file name extension .py), a package is a directory. To make<br />

Python treat it as a package, it must contain a file (module) named __init__.py. The contents<br />

of this file will be the contents of the package, if you import it as if it were a plain module. For<br />

example, if you have a package named constants, and the file constants/__init__.py contains<br />

the statement PI = 3.14, you would be able to do the following:<br />

import constants<br />

print constants.PI<br />

To put modules inside a package, simply put the module files inside the package directory.<br />

For example, if you wanted a package called drawing, which contained one module called<br />

shapes and one called colors, you would need the files and directories (UNIX pathnames)<br />

shown in Table 10-1.<br />

Table 10-1. A Simple Package Layout<br />

File/Directory<br />

~/python/<br />

~/python/drawing/<br />

~/python/drawing/__init__.py<br />

~/python/drawing/colors.py<br />

~/python/drawing/shapes.py<br />

Description<br />

Directory in PYTHONPATH<br />

Package directory (drawing package)<br />

Package code (“drawing module”)<br />

colors module<br />

shapes module<br />

In Table 10-1, it is assumed that you have placed the directory ~/python in your PYTHONPATH. In<br />

Windows, simply replace ~/python with c:\python and reverse the direction of the slashes (to<br />

backslashes).<br />

With this setup, the following statements are all legal:<br />

import drawing<br />

# (1) Imports the drawing package<br />

import drawing.colors # (2) Imports the colors module<br />

from drawing import shapes # (3) Imports the shapes module

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!