Types

Generics and TypeVar

Generics preserve type information across reusable functions and classes.

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
Ada
TFN[T]T
A generic preserves the input type through the call: the same T flows in and out of fn[T].

Reusing 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

See also

Run the complete example

Example code

Expected output

1
Ada
('x', 'y')
T

Execution time appears here after you run the example.