← retour aux snippets

typing: Literal et Annotated pour clarifier les API

Restreindre les valeurs et attacher des métadonnées de type.

python typing #typing

objectif

Restreindre les valeurs et attacher des métadonnées de type.

code minimal

from typing import Literal, Annotated, get_type_hints
Mode = Literal["r","w","a"]
size_t = Annotated[int, "bytes"]
def open_custom(mode: Mode, size: size_t) -> bool: return mode in ("r","w","a")
hints = get_type_hints(open_custom)
print("mode" in hints and "size" in hints)  # attendu: True

utilisation

from typing import Literal
def level(x: Literal["low","mid","high"]) -> str: return x
print(level("low") == "low")

variante(s) utile(s)

from typing import Annotated, get_origin
T = Annotated[int, "bytes"]
print(get_origin(T) is int)

notes

  • Literal restreint à des constantes; Annotated ajoute un contexte.
  • Les vérifieurs statiques (mypy, pyright) en tirent profit.