← retour aux snippets

TypedDict: Required et NotRequired (3.11+)

Exprimer des champs optionnels/obligatoires dans des dicts typés.

python typing #dict

objectif

Exprimer des champs optionnels/obligatoires dans des dicts typés.

code minimal

from typing import TypedDict, Required, NotRequired

class User(TypedDict, total=False):
    id: Required[int]
    name: NotRequired[str]

u: User = {"id": 1}
print("id" in u and "name" not in u)  # attendu: True

utilisation

from typing import TypedDict
class Cfg(TypedDict, total=False):
    host: str; port: int
cfg: Cfg = {"host":"localhost"}
print("host" in cfg)

variante(s) utile(s)

from typing import TypedDict
class Point(TypedDict):
    x: int; y: int
p: Point = {"x":1,"y":2}
print(p["x"] == 1)

notes

  • total=False rend les clés optionnelles par défaut.
  • Required/NotRequired affinent clé par clé.