After this lesson you can organise a program into a package of modules, import between them correctly, and avoid the most common import error.
From module to package
A module is one file. Once a project has a handful of related files, you group them in a folder. A folder of modules, marked by a file named __init__.py, is a package. You use it with dotted names: shop.pricing means "the module pricing inside the package shop".
Let us build a small one for the shop. The folder will be called shop and sit next to a main script. Here are the files.
#file: shop/__init__.py
"""A tiny package for shop calculations."""#file: shop/pricing.py
TAX_RATE = 0.18
def add_tax(amount):
return round(amount * (1 + TAX_RATE), 2)#file: shop/inventory.py
from .pricing import add_tax
STOCK = {"tea": 40, "milk": 12}
def stock_value(prices):
total = sum(prices[name] * count for name, count in STOCK.items())
return add_tax(total)#file: shop/reports/__init__.py#file: shop/reports/daily.py
from ..inventory import STOCK
from shop.pricing import add_tax
def summary():
return f"{len(STOCK)} products in stock, tax on 100 is {add_tax(100)}"#file: main.py
from shop import inventory
from shop.reports import daily
print(inventory.stock_value({"tea": 5, "milk": 3}))
print(daily.summary())Here is the layout, listing only the Python files:
find . -name "*.py" | sort./main.py
./shop/__init__.py
./shop/inventory.py
./shop/pricing.py
./shop/reports/__init__.py
./shop/reports/daily.pyThe role of init.py
The file __init__.py runs when the package is first imported. In the example the shop one holds only a docstring, and shop/reports/__init__.py is empty. An empty file is perfectly normal: its presence is what matters. Later you might use it to expose a friendlier interface, which you will see below. Modern Python can also import a folder without __init__.py (a "namespace package"), but those behave differently, so for your own projects, add the file.
Importing from a package
Absolute imports spell out the full path from the top of the project:
import shop
from shop.pricing import add_tax
from shop import inventory
print(shop.__doc__)
print(add_tax(200))
print(inventory.STOCK)A tiny package for shop calculations.
236.0
{'tea': 40, 'milk': 12}A submodule is not available just because you imported the package. import shop does not load shop.pricing by itself unless the package's __init__.py imports it, so import the submodule you need.
Relative imports
Inside a package, modules can refer to each other with dots. One dot means "this package" and two dots mean "the package above". In inventory.py above, from .pricing import add_tax loads the neighbouring module. In reports/daily.py, from ..inventory import STOCK goes up one level first. Relative imports keep working if you rename the top-level package. Absolute imports, as used for shop.pricing in the same file, are often easier to read. Pick one style and stay consistent.
Now run the main script from the project folder:
python3 main.py278.48
2 products in stock, tax on 100 is 118.0The relative import trap
Relative imports only work when the file is loaded as part of its package. If you run a file inside the package directly, Python treats it as a loose script with no parent, and the dots have nothing to refer to:
python3 shop/reports/daily.py 2>&1 | tail -1ImportError: attempted relative import with no known parent packageThe fix is to run something outside the package that imports it, as main.py does. Use python3 -m shop.reports.daily if you need to run a module inside a package directly.
A friendlier package interface
Users should not need to know which file holds each function. You can re-export names in __init__.py:
#file: tidy/__init__.py
from .helpers import clean
__all__ = ["clean"]#file: tidy/helpers.py
def clean(text):
return " ".join(text.split())from tidy import clean
print(clean(" too many spaces "))too many spacesThe list __all__ says which names are public when someone writes from tidy import *. It is also a helpful note for readers.
A sensible project layout
A small project can follow a simple shape:
shop-report/
main.py the script you run
requirements.txt packages to install
shop/ your package
__init__.py
pricing.py
inventory.py
tests/ test files (see the testing lesson)
.gitignore lists .venv and other generated filesKeep one entry point at the top, put reusable code in the package, and keep tests beside, not inside, it. Avoid very deep nesting. Two or three levels are enough for most programs. Avoid circular imports too, where module A imports B and B imports A, by moving shared code into a third module.
Where the code should go
A reasonable question is when to turn a module into a package. A simple guide is to wait until a file passes a few hundred lines, or contains two or three clearly separate topics, and then split it by topic. In the shop example, price calculations live in one module and stock handling in another, so each file has one theme and a name that tells you what is inside.
You can also see a package's contents from Python itself. The __name__ attribute shows how a package or module is known to Python:
import shop
print(shop.__name__)
print(shop.inventory.__name__)shop
shop.inventoryNotice that shop.inventory is available here because an earlier example already imported that submodule. Python keeps loaded submodules as attributes of the package.
Common mistakes
- Running a package file directly when it uses relative imports.
- Forgetting
__init__.pyand then wondering why imports behave oddly. - Circular imports. Move the shared part into a third module.
- Naming a package after a standard module, such as
randomortest. - Starting Python from the wrong folder, so the package is not on the search path.
- Importing a submodule that was never loaded and getting an AttributeError.
Exercise
Make a package called greeter with a module hello.py containing say(name) that returns "Hello, <name>". In __init__.py, re-export say. Then import it with from greeter import say.
Show one possible answer
#file: greeter/__init__.py
from .hello import say#file: greeter/hello.py
def say(name):
return f"Hello, {name}"from greeter import say
print(say("Asha"))Hello, AshaKey points
- A package is a folder of modules. A file named __init__.py marks the folder as a package and runs when the package is imported.
- Import from a package with dotted names, such as from shop.pricing import add_tax.
- Inside a package, relative imports such as from .pricing import add_tax refer to sibling modules.
- A file that uses relative imports must be run as part of the package, not directly.
- Keep a simple layout: a top-level script, your package folder, and tests next to it.