msgspec
msgspec copied to clipboard
Allow None in dec_hook
trafficstars
Let's say CustomType cannot parse correctly obj, I would like to return None as it is a valid type as defined in MyStruct. Why is it generating a ValidationError ? How can I return None in this example ?
from typing import Any
import msgspec
class CustomType(str):
pass
class MyStruct(msgspec.Struct):
name: CustomType | None
def dec_hook(type_: type, obj: Any) -> Any:
if type_ is CustomType:
# we are calling CustomType(obj) but it returns None
return None
msgspec.convert({"name": "test"}, MyStruct, dec_hook=dec_hook)
This would return:
ValidationError: Expected `CustomType`, got `NoneType` - at `$.name