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.
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:
python-dataclasses-serialization/dataclasses_serialization/serializer_base/union.py
Line 22 in 00fbd28
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:
I think union serialization must save original type in dump.