Skip to content

Deserializing of Union type made in brute force way and can restore instance of different class #20

Description

@telegram-toys

Update:
this is described in documentation:
Deserialize a Union type, by trying each type in turn, and returning the first that does not raise a DeserializationError._
But still looks like not useful :(

Hi,
it looks like abandoned project and I want to keep message for future users.

On serialization of Union type no information about original type saved into dump.
On deserialization all the types in Union are tried in loop in order to recover object:

def union_deserialization(type_, obj, deserialization_func=noop_deserialization):

If you have two classes with same field set then you will always get instance of class that situated earlier in Union type variants list:

import dataclasses

from dataclasses_serialization.json import JSONSerializer


@dataclasses.dataclass
class A:
    value: int
    message: str


@dataclasses.dataclass
class B:
    value: int
    message: str


@dataclasses.dataclass
class UnionC:
    nested: A | B


original = UnionC(nested=B(value=5, message='hello'))
print('original:', original)
# original: UnionC(nested=B(value=5, message='hello'))

dump = JSONSerializer.serialize(original)
print('serialized:', dump)
# serialized: {'nested': {'value': 5, 'message': 'hello'}}

restored = JSONSerializer.deserialize(UnionC, dump)
print('restored:', restored)
# restored: UnionC(nested=A(value=5, message='hello'))

I think union serialization must save original type in dump.

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