← retour aux snippets

typing.assert_never: exhaustivité des match/case

Forcer l'exhaustivité des branches au typage statique (3.11+).

python typing #typing#match

objectif

Forcer l’exhaustivité des branches au typage statique (3.11+).

code minimal

from typing import Literal, assert_never

def handle(x: Literal["a","b"]) -> int:
    if x == "a":
        return 1
    elif x == "b":
        return 2
    else:
        assert_never(x)  # unreachable si exhaustif
        return 0

print(handle("a") == 1)  # attendu: True

utilisation

from typing import Union, assert_never
def f(u: Union[int, str]) -> int:
    if isinstance(u, int):
        return u
    if isinstance(u, str):
        return len(u)
    assert_never(u)
print(f(3) == 3 and f("xx") == 2)

variante(s) utile(s)

from typing import assert_never
print(callable(assert_never))

notes

  • Provoque une erreur de type si une branche est manquante lors de l’analyse statique.
  • À l’exécution, lève une AssertionError si appelée.