16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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 in<strong>to</strong> 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 s<strong>to</strong>red in a file (with the file name extension .py), a package is a direc<strong>to</strong>ry. To make<br />

<strong>Python</strong> 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 <strong>to</strong> 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 direc<strong>to</strong>ry.<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 direc<strong>to</strong>ries (UNIX pathnames)<br />

shown in Table 10-1.<br />

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

File/Direc<strong>to</strong>ry<br />

~/python/<br />

~/python/drawing/<br />

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

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

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

Description<br />

Direc<strong>to</strong>ry in PYTHONPATH<br />

Package direc<strong>to</strong>ry (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 direc<strong>to</strong>ry ~/python in your PYTHONPATH. In<br />

Windows, simply replace ~/python with c:\python and reverse the direction of the slashes (<strong>to</strong><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!