Preserve Type Relationships with TypeVar
Core idea
A generic function describes how a type chosen at a call site relates to other parameters or the result. TypeVar T allows the checker to connect a value and its returned type, rather than losing information to object. T is not a runtime test. A nonempty sequence is a separate input contract.
from typing import TypeVarfrom collections.abc import SequenceT = TypeVar('T')def last(items: Sequence[T]) -> T: return items[-1]print(last([4, 9]), last(('a', 'b')))A checker can infer int and str respectively. Indexing returns the final item.
Preserve an optional result
from typing import TypeVarT = TypeVar('T')def first_or_none(items: list[T]) -> T | None: return items[0] if items else Noneprint(first_or_none([12]), first_or_none([]))The explicit empty branch returns None; generic typing does not enforce list length.
Common mistake
Using object as the return type hides the relationship. Do not call isinstance(value, T); T is not a runtime class.
Practice
Write a generic function returning the first item or a supplied default; compare inferred types for integers and strings in a checker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TypeVar and generic functions
Check your understanding of typevar and generic functions.
What is printed?
from typing import TypeVarT=TypeVar('T')def box(x:T)->tuple[T]: return (x,)print(box(7))What is printed?
from typing import TypeVarT=TypeVar('T')def pick(x:T)->T: return xprint(type(pick('a')).__name__)What does a shared T express?
What does Sequence[T] not guarantee?