← retour aux snippets

types.MappingProxyType: vue en lecture seule d'un dict

Empêcher la modification d'un dict exposé à l'extérieur.

python typing #types#immutable

objectif

Empêcher la modification d’un dict exposé à l’extérieur.

code minimal

from types import MappingProxyType
d = {"a": 1}
ro = MappingProxyType(d)
print(ro["a"] == 1 and "update" not in dir(ro))  # attendu: True

utilisation

from types import MappingProxyType
conf = MappingProxyType({"x": 1})
try:
    conf["x"] = 2
    print(False)
except TypeError:
    print(True)

variante(s) utile(s)

from types import MappingProxyType
d = {"k": "v"}; ro = MappingProxyType(d); d["k"] = "w"
print(ro["k"] == "w")

notes

  • La vue reflète les changements du dict source, mais reste non modifiable.
  • Exposez MappingProxyType dans les APIs pour l’immuabilité.