Phase 14 of 25 · Topic 14.1

Type Hinting Fundamentals (Union, Optional, TypeVar, Generic)

1Concept

Python 3.5+ type hints provide static type safety without runtime performance penalties. Modern syntax (PEP 604) uses `int | str` instead of `Union[int, str]`, and `str | None` instead of `Optional[str]`. `TypeVar` creates generic classes and functions.

2Architecture Diagram

def process(val: int | str) -> list[str]: ... (Statically checked by mypy and IDEs!)

3Code Example

Python 3.12
from typing import TypeVar, Generic

T = TypeVar("T")

class GenericRepository(Generic[T]):
    def __init__(self):
        self._items: list[T] = []

    def save(self, item: T) -> None:
        self._items.append(item)

    def get_all(self) -> list[T]:
        return self._items

repo: GenericRepository[str] = GenericRepository()
repo.save("Entity-101")
print(f"Repository items: {repo.get_all()}")

4Expected Output

Repository items: ['Entity-101']

5Key Takeaways

  • Type annotations are purely metadata; CPython does not enforce them at runtime without tools like Pydantic.
  • Use `int | float` (Python 3.10+) instead of verbose `typing.Union`.
  • `reveal_type(var)` is a Mypy pseudo-function to inspect inferred types.