apischema icon indicating copy to clipboard operation
apischema copied to clipboard

Custom coerce and Union

Open sylflo opened this issue 2 years ago • 0 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 https://github.com/wyfo/apischema/commit/37bb1d4d7be5eb317a119fa4196e010e39767ada

sylflo avatar May 18 '22 09:05 sylflo