🌱 Junior Track 14 of 14

14. Modules & Packages

Organize professional Python applications: `import`, `from ... import`, `aliases`, `__init__.py`, `__name__ == '__main__'`, absolute vs. relative imports, and package architecture.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 14 — MODULES & PACKAGES
# ==============================================================================

# 1. Standard Imports & Aliases
import math as m
from datetime import datetime as dt, timedelta as td

# 2. Function within custom module
def calculate_circle_area(radius: float) -> float:
    """Uses math alias 'm' to compute circle area."""
    return m.pi * (radius ** 2)

def get_future_date(days_ahead: int) -> str:
    """Uses datetime alias 'dt' and timedelta alias 'td'."""
    future = dt.now() + td(days=days_ahead)
    return future.strftime("%Y-%m-%d %H:%M:%S")

# 3. Package Structure Demonstration
"""
mypackage/
├── __init__.py      # Package initialization & public API export
├── math_tools.py    # Submodule with math utilities
└── string_tools.py  # Submodule with string utilities
"""

# 4. The __name__ == "__main__" Idiom
if __name__ == "__main__":
    print(f"[MODULE EXECUTION] Executing {__file__} as standalone script.")
    print(f"Circle Area (r=5): {calculate_circle_area(5):.2f}")
    print(f"Date +7 days: {get_future_date(7)}")
🌱 Junior Track 14 Master Reference

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__.

# mypackage/__init__.py
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).

⭐ Rate Track 14: Modules & Packages (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 13. File Handling 🌱 Junior Hub 15. Virtual Environments →