Packages

A package is a module that contains other modules. Some or all of the 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. Packages can also live in ZIP files; in the following, I explain the case in which the package lives on the filesystem, since the case in which a package lives in a ZIP file is strictly analogous, relying on the hierarchical filesystem-like structure inside the ZIP file.

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. The module-body of a package is loaded when you first import the package (or any of the package’s modules) and behaves in all respects like any other Python module. The other .py files in directory P are the modules of package P. Subdirectories of P containing _ _init_ _.py files are subpackages of P. (In Python 2.5, all subdirectories of P are subpackages of P, whether such subdirectories contain _ _init_ _.py files or not.) 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’s module-body is always loaded before any module in the package is loaded.) If you use the syntax import P.M, variable P is bound to the module object of package ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.