See All Titles |
![]() ![]() PackagesA 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:
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 StructureThe 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 PackagesPackages 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.
|
© 2002, O'Reilly & Associates, Inc. |