3.13. Typing TypeVar
Typeshed contains external type annotations for the Python standard library and Python builtins, as well as third party packages as contributed by people external to those projects.
3.13.1. TypeVar
>>> from typing import TypeVar
TypeVar is a special class that is used to define type variables in function signatures. It is used to declare a type variable that can be used in a function signature. Type variables are used to define generic functions that can work with different types of data.
>>> T = TypeVar('T', int, float)
>>>
>>> def add(a: T, b: T) -> T:
... return a + b
You can also use TypeVar to define a type variable that is a subclass of a specific type. For example, you can define a type variable that is a subclass of int.
>>> T = TypeVar('T', bound=int)
>>>
>>> def add(a: T, b: T) -> T:
... return a + b
3.13.2. TypeGuard
https://docs.python.org/3/library/typing.html#typing.TypeGuard
3.13.3. Use Case - 1
>>> from typing import TypeVar
>>>
>>>
>>> T = TypeVar('T', int, float)
>>> type Vector[T] = tuple[T, T]
>>>
>>>
>>> def product(data: Vector[T]) -> T:
... return sum(x*y for x,y in data)