Organize Python Modules into Packages
Core idea
A package is a module that can contain submodules. A regular package typically has a directory with __init__.py; Python also supports namespace packages without that file. Start with regular packages to group related code and use dotted import paths.
Load a submodule
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_shop/__init__.py
bm_shop/cost.py
def total(price, count): return price * countSave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Output: 20. The directory bm_shop is a regular package and cost is its submodule.
Expose a selected package function
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_shop/__init__.py
from bm_shop.cost import totalbm_shop/cost.py
def total(price, count): return price * countSave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
from bm_shop import totalprint(total(7, 3))Output: 21. init.py imports the function from the submodule into the package namespace.
Run a package entry point
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_shop/__init__.py
bm_shop/cost.py
def total(price, count): return price * countSave the following code as bm_shop/__main__.py and run python -m bm_shop from the new directory. Use a fresh directory for each example.
Output: 18. With -m, Python finds the package and executes its main.py file as the entry point.
Common mistake
A folder name alone does not guarantee that imports resolve from every working directory. Run these projects from their parent directory. Do not name your own modules after standard library modules such as math or json.
Practice
Add a second module to bm_shop for a delivery fee. Import each function from its own submodule, then choose which function to expose through init.py.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Organize package paths
Check your understanding of packages.
Which layout is a regular package named bm_shop with a cost submodule?
From the parent directory, how do you run a package bm_shop with __main__.py?
What can __init__.py do in a regular package?
What distinguishes a namespace package from an ordinary regular package?