Custom coerce and Union
sylflo opened this issue · comments
I have the following code
import json
from dataclasses import dataclass
from typing import Any, Mapping, Sequence, Union
from apischema import deserialize
def _coerce_json(cls, data):
if not isinstance(data, cls) and isinstance(data, str):
return json.loads(data)
else:
return data
@dataclass
class MyClass:
my_property: Union[Sequence[Any], Mapping[str, Any]]
ret = deserialize(MyClass, {"my_property": '{"test": 2}'}, coerce=_coerce_json)
When using Union[Sequence[Any], Mapping[str, Any]]
and trying to execute the code, I get the following error
apischema.validation.errors.ValidationError: ValidationError(messages=[], children={'my_property': ValidationError(messages=['expected type array, found string', 'expected type object, found string'], children={})})
However if I remove the Union
like this my_property: Mapping[str, Any]
, this is working and the object is deserialized properly
EDIT: This behavior seems to be introduced by this commit 37bb1d4
This PR #501 seems to fix the problem