Skip to content

Union of generics doesn't work #301

@Kobzol

Description

@Kobzol

Hi! Thanks for this wonderful library (serde FTW!). I was experimenting with it and noticed a strange behavior that happens when generics and union is combined within a dataclass nested field. Here's a minimal reproduction:

@serde
class ClassA:
    a: int


@serde
class ClassB:
    a: int


T = TypeVar("T")


@serde
class Wrapper(Generic[T]):
    inner: T
    meta: str


InnerType = Union[Wrapper[ClassA], Wrapper[ClassB]]


@serde
class Root:
    config: InnerType


wrapper = Wrapper(inner=ClassA(a=1), meta="foo")
print(from_dict(InnerType, to_dict(wrapper)))
# Wrapper(inner=ClassA(a=1), meta='foo') - right

root = Root(wrapper)
print(from_dict(Root, to_dict(root)))  
# Root(config=Wrapper(inner={'a': 1}, meta='foo')) - wrong, ClassA was not deserialized

Basically, when I have a union of generics, and serialize + deserialize it, it deserializes correctly. However, when the same thing is deserialized as a field of another serde dataclass, it doesn't serialize the nested field correctly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions