Chapter 24. Module Packages
So far, when weâve imported modules, weâve been loading files. This represents typical module usage, and itâs probably the technique youâll use for most imports youâll code early on in your Python career. However, the module import story is a bit richer than I have thus far implied.
In addition to a module name, an import can name a directory path. A directory of Python code is said to be a package, so such imports are known as package imports. In effect, a package import turns a directory on your computer into another Python namespace, with attributes corresponding to the subdirectories and module files that the directory contains.
This is a somewhat advanced feature, but the hierarchy it provides 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 to resolve import ambiguities when multiple program files of the same name are installed on a single machine.
Because it is relevant to code in packages only, weâll also
introduce Pythonâs recent relative imports model
and syntax here. As weâll see, this model modifies search paths in 3.X,
and extends the from
statement
for imports within packages in both 2.X and 3.X. This model can make such
intrapackage imports more explicit and succinct, but comes with some
tradeoffs that can impact your programs.
Finally, for readers using Python 3.3 and later, its new namespace package ...
Get Learning Python, 5th 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.