17.3 Why Use Package Imports?
If you're new to Python, make sure that
you've mastered simple modules before stepping up to
packages, as they are a somewhat advanced feature of Python. They do
serve useful roles, especially in larger programs: they make imports
more informative, serve as an organizational tool, simplify your
module search path, and can resolve ambiguities.
First of all, because package imports give some directory information
in program files, they both make it easier to locate your files, and
serve as an organizational tool. Without package paths, you must
resort to consulting the module search to find files more often.
Moreover, if you organize your files into subdirectories for
functional areas, package imports make it more obvious what role a
module plays, and so make your code more readable. For example, a
normal import of a file in a directory somewhere on the module search
path:
import utilities
bears much less information than an import that includes path
information:
import database.client.utilities
Package imports can also greatly simply your
PYTHONPATH or .pth file
search path settings. In fact, if you use package imports for all
your cross-directory imports, and you make those package imports
relative to a common root directory where all your Python code is
stored, you really only need a single entry on your search path: the
common root.
|