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. ...
Get Python in a Nutshell 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.