Chapter 17. Module Packages
So far, when we’ve imported a module, we’ve been loading files. This represents typical module usage, and is what you will probably use for most imports you’ll code early on in your Python career. The module import story is a bit more rich than we have thus far implied.
Imports can name a directory path, in addition to a module name. When they do, they are known as package imports—a directory of Python code is said to be a package. This is a somewhat advanced feature, but turns out to be handy for organizing the files in a large system, and tends to simplify module search path settings. As we’ll see, package imports are also sometimes required in order to resolve ambiguities when multiple programs are installed on a single machine.
Package Import Basics
Here’s how package imports
work. In the place where we have been naming a simple file in
import statements, we can instead list a path of
names separated by periods:
The same goes for
from dir1.dir2.mod import x
The “dotted” path in these
statements is assumed to correspond to a path through the directory
hierarchy on your machine, leading to the file
mod.py (or other file type). That is, there is
dir1, which has a subdirectory
dir2, which contains a module file
mod.py (or other suffix).
Furthermore, these imports imply that
within some container directory
dir0, which is accessible on the Python module search path. In other words, the two import statements ...