Skip to content
AgileLogics
4 min read

Generics and Typing

Prerequisites: Functions

Python's type hints can describe a function that works generically across types, while still being checked by tools like mypy before the code even runs.

from typing import TypeVar

T = TypeVar("T")

def first_item(items: list[T]) -> T:
    return items[0]

first_item([1, 2, 3])         # inferred as int
first_item(["a", "b", "c"])   # inferred as str

Type hints are never enforced by Python itself at runtime — they're checked by a separate tool (mypy) as a way to catch mistakes before running the code, not a hard runtime guarantee.