Skip to content

Allow None in dec_hook #855

@korlaz

Description

@korlaz

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions