Generics and relationships between types
Write one helper that returns the first element of a sequence while preserving its element type for callers. Start with the type hints lesson.
On this page
Read the model
A type variable names a relationship between positions in a signature. In first, the T inside Sequence and the T after the arrow represent the same choice for a given call. Sequence lets the function use indexing on a list, a tuple, or another compatible sequence.
Follow the example
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def first(values: Sequence[T]) -> T:
if not values:
raise ValueError("empty sequence")
return values[0]
print(first([7, 12]) + 1)
print(first(("tea", "coffee")).upper())The first call binds T to int for type checking, so adding 1 makes sense. The second call uses strings and the result supports upper. The program prints 8 and TEA. At runtime both calls use the same function body.
Change one condition
Call first with an empty list. It raises ValueError before indexing. To support returning None instead, change both the empty branch and the return annotation to T | None. Callers must handle that possibility before using integer or string methods.