< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204174049228072020001127037

Packages

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages. Packages were added to Python 1.5 to aid with a variety of problems including:

  • Adding hierarchical organization to flat namespace

  • Allowing developers to group-related modules

  • Allowing distributors to ship directories vs. bunch of files

  • Helping resolve conflicting module names

Along with classes and modules, packages use the familiar attribute/dotted attribute notation to access their elements. Importing modules within packages use the standard import and from-import statements.

Directory Structure

The example package directory structure below is available for you to experiment with on the CD-ROM accompanying this book. Just browse the code samples and navigate to Chapter 12.

						
Phone/
    __init__.py
    Voicedta/
        __init__.py
        Pots.py
        Isdn.py
    Fax/
        __init__.py
        G3.py
    Mobile/
        __init__.py
        Analog.py
        Digital.py
    Pager/
        __init__.py
        Numeric.py

					

Phone is top-level package and Voicedta, etc., are subpackages. Import subpackages by using import like this:

						
import Phone.Mobile.Analog

Phone.Mobile.Analog.dial()

					

Alternatively, you can use from-import in a variety of ways:

The first way is importing just the top-level subpackage and referencing down the subpackage tree using the attribute/dotted notation:

						
from Phone import Mobile

Mobile.Analog.dial('4 555–1212')

					

Further more, we can do down one more subpackage for referencing:

						
from Phone.Mobile import Analog

Analog.dial('555–1212')

					

In fact, you can go all the way down in the subpackage tree structure:

						
from Phone.Mobile.Analog import dial

dial('555–1212')

					

In our above directory structure hierarchy, we observe a number of __init__.py files. These are initializer modules that are required when using from-import to import subpackages, but should otherwise exist though they can remain empty.

Using from-import with Packages

Packages also support the from-import all statement:

						
from
							package.module
							import *

					

However, such a statement is too operating system filesystem-dependent for Python to make the determination which files to import. Thus the __all__ variable in __init__.py is required. This variable contains all the module names that should be imported when the above statement is invoked if there is such a thing. It consists of a list of module names as strings.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.