🌱 Junior Track 23 of 23

23. Type Hints & Static Typing

Write production-ready, type-safe Python using modern annotations (`def get_user(id: int) -> dict[str, str]`), `Optional`, `Union`, `Callable`, `TypeVar`, custom `Generic` classes, and static checking tools like `mypy`.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 23 — TYPE HINTS & STATIC TYPE CHECKING
# ==============================================================================
from typing import Optional, Union, Any, Callable, TypeVar, Generic

# 1. Type Aliases
UserPayload = dict[str, str | int | list[str]]

# 2. Modern Built-in Generics & Optional Return Type
def get_user(user_id: int) -> dict[str, str]:
    return {"id": str(user_id), "name": "Alice", "role": "admin"}

def find_by_email(email: str) -> Optional[UserPayload]:
    if email == "alice@example.com":
        return {"name": "Alice", "age": 28, "skills": ["Python", "Flask"]}
    return None

# 3. Callable & Higher-Order Functions
def transform_scores(
    scores: list[int],
    operation: Callable[[int], int]
) -> list[int]:
    return [operation(s) for s in scores]

# 4. TypeVar & Custom Generic Class
T = TypeVar("T")

class DataContainer(Generic[T]):
    def __init__(self, item: T) -> None:
        self._item: T = item

    def get_data(self) -> T:
        return self._item

if __name__ == "__main__":
    user = get_user(101)
    print("User Dict:", user)

    result = find_by_email("alice@example.com")
    print("Found Payload:", result)

    doubled = transform_scores([10, 20, 30], lambda x: x * 2)
    print("Doubled Scores:", doubled)

    container = DataContainer[int](42)
    print("Container Value:", container.get_data())
🌱 Junior Track 23 Master Reference

23. Type Annotations & Mypy Quick Reference

📊 Modern Type Hinting Syntax Matrix

Concept Modern Syntax (Python 3.10+) Legacy Syntax (typing) Use Case
Lists list[int] List[int] Homogeneous sequence of integers.
Dictionaries dict[str, int] Dict[str, int] Key-value mapping.
Unions int | str Union[int, str] Multiple acceptable types.
Optionals str | None Optional[str] Nullable string values.
Callables Callable[[int], str] Callable[[int], str] Function signature annotations.
Generics Generic[T] Generic[T] Reusable type-parameterized classes.

⭐ Rate Track 23: Type Hints & Static Analysis (1 to 5 Stars)

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

★ ★ ★ ★ ★
← 22. Functional Programming 🌱 Junior Hub 24. Dataclasses →