Lesson 2 of 6 · Modules and the Standard Library · 3 min read · Updated
Packages and __init__.py
Grouping related modules into a folder you can import from.
When one file of functions grows into several, group them in a folder. A folder of modules that Python can import from is a package.
# school/ the package folder
# __init__.py marks the folder as a package
# marks.py def average(values): ...
# report.py def card(name, marks): ...
# main.py next to the school folder
from school import marks
from school.report import card
print(marks.average([72, 85, 91]))
print(card("Priya", 87))
- Folders become dotted names:
school/report.pyis imported asschool.report. - All the import forms from the previous lesson work:
import school.marks,from school import marks,from school.report import card. - Packages can hold packages:
school/exams/results.pyisschool.exams.results.
What __init__.py is for
# school/__init__.py
"""Tools for marks and report cards."""
from .marks import average
from .report import card
__all__ = ["average", "card"]
__init__.py runs the first time the package is imported. It can be empty — its presence alone marks the folder as a package — or it can bring the most useful names up to the top, so callers write from school import average without knowing which file it lives in. The dot in from .marks means "from this package".
Note
Python 3 can import a folder without __init__.py (a "namespace package"), but include one anyway: it makes the intent clear, and it is the only place to put package-level set-up.
Warning
Relative imports such as from .marks import average work only inside a package. Run school/report.py directly and they fail with ImportError: attempted relative import with no known parent package. Run the program from the folder above instead, with python -m school.report or through main.py.
A file is at shop/billing/tax.py. How do you import it?
Try this now
- Create a
calcpackage withbasic.py(add, subtract) andadvanced.py(power, factorial), and use both from main.py. - Put
from .basic import addincalc/__init__.pyand confirmfrom calc import addnow works.
Create a free account to save your progress, or sign in.