A Python package groups related modules under a common name. Where a module keeps code in one file, a package uses a directory and can contain subpackages. This gives larger projects a way to separate responsibilities without leaving modules unconnected. section 18.1 section 18.0
The directory structure determines how code is named and imported:
- Put related .py modules in a package directory; use subdirectories when a further split is useful. A module at mathproj/comp/numeric/n1.py is imported as mathproj.comp.numeric.n1. section 18.3 section 18.3.3
- An __init__.py file marks a directory as a package and runs when that package is first loaded. It may be empty, or it may initialize names in the package namespace. section 18.3.1 section 18.3.2
- Import the submodule you need: import mathproj alone does not load every module beneath it. Importing a nested module loads its parent packages first. section 18.3.3
A small package interface
Suppose word_count has cleaning.py, counter.py, and exceptions.py. Its __init__.py can import clean_line from cleaning.py and count_words from counter.py. A caller can then write import word_count and call word_count.clean_line(line) without naming the internal module. The files remain separate, while selected functions appear at the package’s top level. section 18.6.2
import mathproj.comp.numeric.n1 Hello from mathproj.comp init Hello from numeric init mathproj.comp.numeric.n1.g() version is 1.03 Called function h in module n2
The nested import prints messages from parent __init__.py files before the example calls a function in the imported module. section 18.3.3
Keep the hierarchy shallow unless the collection is unusually large. __all__ can affect wildcard imports, but an underscore-prefixed name is the preferred way here to exclude a name. This directory-and-module meaning of package is distinct from a distributable package uploaded to a repository; building that distribution is a separate task. section 18.5 section 18.0







