← retour aux snippets

typing.TypeVar: bornes et contraintes

Restreindre un type générique à une hiérarchie ou un ensemble donné.

python typing #typing#generics

objectif

Restreindre un type générique à une hiérarchie ou un ensemble donné.

code minimal

from typing import TypeVar, Iterable
TNum = TypeVar("TNum", int, float)

def total(xs: Iterable[TNum]) -> float:
    return float(sum(xs))

print(total([1,2,3]) == 6.0)  # attendu: True

utilisation

from typing import TypeVar
TBounded = TypeVar("TBounded", bound=BaseException)
def identity(e: TBounded) -> TBounded:
    return e
print(isinstance(identity(ValueError()), BaseException))

variante(s) utile(s)

from typing import TypeVar
print(isinstance(TypeVar("X"), TypeVar))

notes

  • constraints: énumérez des types autorisés; bound: borne supérieure unique.
  • Aide les checkers à inférer des signatures plus précises.