← retour aux snippets

typing.NewType: types distincts à l'analyse statique

Différencier des identifiants (UserId, ProductId) sans coût runtime.

python typing #typing#safety

objectif

Différencier des identifiants (UserId, ProductId) sans coût runtime.

code minimal

from typing import NewType
UserId = NewType("UserId", int)
ProductId = NewType("ProductId", int)
u = UserId(1); p = ProductId(1)
print(int(u) == int(p) == 1)  # attendu: True

utilisation

from typing import NewType
OrderId = NewType("OrderId", str)
def get_order(o: OrderId) -> str:
    return str(o)
print(get_order(OrderId("A-1")).startswith("A-"))

variante(s) utile(s)

from typing import NewType
print(callable(NewType))

notes

  • NewType aide à éviter des confusions entre identifiants de même base.
  • Zéro overhead à l’exécution; bénéfice côté type-checkers uniquement.