Python - Modules
Overview
Estimated time: 25–35 minutes
Structure code with modules and packages. Learn import styles, the module search path, and package layout.
Learning Objectives
- Import modules and names with
import
andfrom ... import ...
. - Understand the module search path and relative imports.
- Create a simple package and use
__init__.py
.
Prerequisites
Import styles
import math
from math import sqrt
from collections import defaultdict as dd
print(math.pi, sqrt(16), dd(int))
Package structure
# project/
# app/
# __init__.py
# util.py
# main.py
# main.py
from app.util import greet
print(greet("Ada"))
Relative imports (inside packages)
# In app/service.py
from .util import greet # relative import within the same package
Common Pitfalls
- Running a module inside a package directly (affects
__package__
). Preferpython -m package.module
. - Using relative imports from a top-level script (use absolute or run as a module).
Checks for Understanding
- What file marks a directory as a package (pre-3.3 and for explicit packages)?
- How do you run a module as a script?
Show answers
__init__.py
python -m package.module
Exercises
- Create a package with two modules and import between them using a relative import.
- Demonstrate running a module with
-m
and explain the difference from running the file path.