Previous Section Next Section

7.3 Packages

A package is a module that contains other modules. Modules in a package may be subpackages, resulting in a hierarchical tree-like structure. A package named P resides in a subdirectory, also called P, of some directory in sys.path. The module body of P is in the file P/_ _init_ _.py. You must have a file named P/_ _init_ _.py, even if it's empty (representing an empty module body), in order to indicate to Python that directory P is indeed a package. Other .py files in directory P are the modules of package P. Subdirectories of P containing _ _init_ _.py files are subpackages of P. Nesting can continue to any depth.

You can import a module named M in package P as P.M. More dots let you navigate a hierarchical package structure. A package is always loaded before a module in the package is loaded. If you use the syntax import P.M, variable P is bound to the module object of package P, and attribute M of object P is bound to module P.M. If you use the syntax import P.M as V, variable V is bound directly to module P.M.

Using from P import M to import a specific module M from package P is fully acceptable programming practice. In other words, the from statement is specifically okay in this case.

A module M in a package P can import any other module X of P with the statement import X. Python searches the module's own package directory before searching the directories in sys.path. However, this applies only to sibling modules, not to ancestors or other more-complicated relationships. The simplest, cleanest way to share objects (such as functions or constants) among modules in a package P is to group the shared objects in a file named P/Common.py. Then you can import Common from every module in the package that needs to access the objects, and then refer to the objects as Common.f, Common.K, and so on.

    Previous Section Next Section