msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Allow None in dec_hook

Open korlaz opened this issue 5 months ago • 0 comments
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

korlaz avatar May 31 '25 00:05 korlaz