You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Struct rename= mapping silently swallows non-KeyError exceptions from __getitem__ #1407
When rename= is a mapping, msgspec looks each field name up with __getitem__ and clears any exception, not just KeyError. A mapping that raises something else (here RuntimeError) is silently ignored, the class is created, and the raw field name is used on the wire. A callable rename= propagates its errors.
fromcollections.abcimportMappingimportmsgspecclassM(Mapping):
def__getitem__(self, k):
ifk=="a":
raiseRuntimeError("boom")
raiseKeyError(k)
def__iter__(self):
returniter(())
def__len__(self):
return0classS(msgspec.Struct, rename=M()):
a: intb: int=0print("EXPECTED: RuntimeError propagated from rename mapping __getitem__")
print("ACTUAL: no error, class created, encoded as", msgspec.json.encode(S(1)).decode())
EXPECTED: RuntimeError propagated from rename mapping __getitem__
ACTUAL: no error, class created, encoded as {"a":1,"b":0}
Expected behavior
Only a missing key (KeyError) should fall back to the field name. Any other exception should propagate when the class is defined, as rename_callable (src/msgspec/_core.c, just above rename_mapping) already does for callables.
rename_mapping (src/msgspec/_core.c:5911-5917) calls PyErr_Clear() on any failure of PyObject_GetItem. A fix is to clear only when PyErr_ExceptionMatches(PyExc_KeyError) and otherwise return NULL.
I have a fix with a regression test ready and will open a pull request for it right after filing this issue; it will link back here.
Activity