liveBook · Manning

Subpackage

As explained in The Quick Python Book, Fourth Edition

A subpackage is a package nested within another package's directory structure.

A subpackage is a package nested inside another package’s directory. It helps organize a large library across related modules without putting everything in one file or at one level. section 18.3 section 18.7

A nested package

In `mathproj/comp/numeric/n1.py`, `numeric` is a subpackage of `comp`, which is itself a subpackage of `mathproj`. Each package directory has an `__init__.py` file; an empty one is often enough. The `n1.py` module imports from both `mathproj` and `mathproj.comp`. section 18.3 section 18.3.1

Import the nested module you need: `import mathproj.comp.numeric.n1`. Importing `mathproj` alone does not load all its subpackages and modules. On the nested import, Python loads `mathproj.comp` and then `mathproj.comp.numeric` before `n1`, executing each package’s `__init__.py` the first time it loads. section 18.3.3

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 import prints messages from both subpackage initializers; calling `mathproj.comp.numeric.n1.g()` then uses code from the nested module. section 18.3.3

Subpackages need an explicit import, either in your code or in a package’s `__init__.py`. Reserve deeper nesting for libraries complex enough to justify it; one or two levels is usually plenty. section 18.7

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through a nested directory example, explicit imports, and initializer execution, but does not develop a larger subpackage design.
Examples
Uses `mathproj.comp.numeric.n1` to show nested imports, initializer messages, and a function call.
What it assumes
Assumes familiarity with Python files and imports while explaining what `__init__.py` does for package directories.
What you can do after
Build it from scratch by nesting package directories with `__init__.py` files and explicitly importing the modules needed.
How it connects
Connects subpackages to Python modules, imports, `__init__.py`, and `__all__`.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.