Types
Generics and TypeVar
A TypeVar stands for a type chosen by the caller. The return type follows the list element type.
Source
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]
print(first([1, 2, 3]))
print(first(["Ada", "Grace"]))Output
1
AdaReusing the same TypeVar expresses a relationship between parameters and results.
Source
def pair(left: T, right: T) -> tuple[T, T]:
return (left, right)
print(pair("x", "y"))Output
('x', 'y')TypeVar is visible at runtime, but the relationship is mainly for type checkers.
Source
print(T.__name__)
print(first.__annotations__)Output
T
{'items': list[~T], 'return': ~T}Notes
- A
TypeVarstands for a type chosen by the caller. - Generic functions avoid losing information to
objectorAny. - Use generics when input and output types are connected.
See also
- related: Type Hints
- prerequisite: Collections Module
- related: Casts and Any
Run the complete example
Expected output
1
Ada
('x', 'y')
T
Execution time appears here after you run the example.