3.12. Typing TypeVar

  • https://github.com/python/typeshed

  • 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.12.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.12.2. TypeGuard

>>> from typing import TypeGuard
>>>
>>>
>>> def is_list_str(iterable: list[object]) -> TypeGuard[list[str]]:
...     return all(isinstance(x,str) for x in iterable)
>>>
>>>
>>> def run(data: list[object]):
...     if is_list_str(data):
...         print(','.join(data))  # type checker knows that data is narrowed to list[str]
...     else:
...         print('Not a list of strings!')  # type checker thinks that data is still list[object]

3.12.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)