-
-
Notifications
You must be signed in to change notification settings - Fork 68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Incorrect Serialization and Deserialization of Union Types #584
Comments
@othmane099 This is the expected behavior. You have to set a different dacite config |
By adding the following @dataclass
class CoreMessage(AvroModel):
messageBody: typing.Union[
MessageTypeOne,
MessageTypeTwo,
]
class Meta:
dacite_config = {
"strict_unions_match": True,
"strict": True,
} The previous example ( mt1 = MessageTypeOne()
core_message = CoreMessage(messageBody=mt1)
serialized = core_message.serialize()
deserialized = CoreMessage.deserialize(serialized)
print(deserialized.messageBody) an exception Could the issue be attributed to the absence of fields within the |
Not really. In your case if you use the following config it should work class Meta:
dacite_config = {
"strict": True,
} In any case, sometimes it is not possible to cover all cases so you will have to play with differentt dacite config |
Thanks for your answer. I encountered another case where the types have same attribute name, for example: from dataclasses_avroschema import AvroModel
from dataclasses import dataclass
import typing
@dataclass
class MessageTypeTwo(AvroModel):
val: str
class Meta:
namespace = "Messages.type.two"
@dataclass
class MessageTypeOne(AvroModel):
val: str
class Meta:
namespace = "Messages.type.one"
@dataclass
class CoreMessage(AvroModel):
messageBody: typing.Union[
MessageTypeOne,
MessageTypeTwo,
]
class Meta:
dacite_config = {
"strict": True,
}
mt2 = MessageTypeTwo("Hello World")
core_message = CoreMessage(messageBody=mt2)
serialized = core_message.serialize()
deserialized = CoreMessage.deserialize(serialized)
print(deserialized.messageBody) Expected: |
Yes, it makes sense. It is impossible to determine which class should be created. Under the hood you get a |
I encountered an issue while using the dataclasses-avroschema package for Avro serialization in Python. When attempting to serialize and deserialize a dataclass with a union type using dataclasses_avroschema, the deserialized object doesn't match the expected type.
Serialize and deserialize an instance of CoreMessage with an instance of MessageTypeTwo:
Expected Result: The print statement should output MessageTypeTwo(val='val').
Actual Result: The print statement outputs MessageTypeOne().
The text was updated successfully, but these errors were encountered: