14. Modules & Packages
Organize professional Python applications: `import`, `from ... import`, `aliases`, `__init__.py`, `__name__ == '__main__'`, absolute vs. relative imports, and package architecture.
🎓 Junior Python Curriculum — Select Module
14. Python Modules & Packages Reference
1️⃣ Import Syntax & Aliasing Options
| Import Syntax | Usage | Example Code |
|---|---|---|
| import module | Imports whole module under namespace. | import math res = math.sqrt(16) |
| import module as alias | Renames module namespace. | import numpy as np arr = np.array([1, 2]) |
| from module import item | Imports specific function/class into local scope. | from os import path p = path.abspath(".") |
| from module import item as alias | Imports item with custom alias name. | from datetime import datetime as dt |
2️⃣ Creating Packages & `__init__.py`
A Python package is simply a directory containing Python files and a special file named __init__.py. The __init__.py marks the directory as a Python package and can export a clean public API using __all__.
from .math_tools import calculate_total
from .string_tools import format_name
__all__ = ["calculate_total", "format_name"]
3️⃣ Absolute vs. Relative Imports
- Absolute Imports: Specify full path from project root. (e.g.,
from cloud_app.main.routes import main). Preferred for readability! - Relative Imports: Use leading dots (
.for current package,..for parent package). (e.g.,from .helpers import sanitize).