| An Introduction to Python by Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 124 pages ISBN 0954161769 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |
6.4.2 Intra-package References
The submodules often need to refer to each other. For example, the
‘surround’ module might use the ‘echo’ module. In fact,
such references are so common that the import statement
first looks in the containing package before looking in the standard
module search path. Thus, the ‘surround’ module can simply use
import echo or from echo import echofilter. If the
imported module is not found in the current package (the package of
which the current module is a submodule), the import
statement looks for a top-level module with the given name.
When packages are structured into subpackages (as with the
‘Sound’ package in the example), there's no shortcut to refer
to submodules of sibling packages--the full name of the subpackage
must be used. For example, if the module
‘Sound.Filters.vocoder’ needs to use the ‘echo’ module
in the ‘Sound.Effects’ package, it can use from Sound.Effects import echo.
Starting with Python 2.5, in addition to the implicit relative imports
described above, you can write explicit relative imports with the
from module import name form of import statement. These explicit
relative imports use leading dots to indicate the current and parent
packages involved in the relative import. From the ‘surround’
module for example, you might use:
from . import echo
from .. import Formats
from ..Filters import equalizer
Note that both explicit and implicit relative imports are based on the
name of the current module. Since the name of the main module is always
"__main__", modules intended for use as the main module of a
Python application should always use absolute imports.
| ISBN 0954161769 | An Introduction to Python | See the print edition |