Skip to content
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

[BUG] to_msgpack doesn't behave properly with Discriminator(include_subtypes=True) #233

Closed
fps7806 opened this issue Jun 26, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@fps7806
Copy link

fps7806 commented Jun 26, 2024

  • mashumaro version: 3.13.1

Description

I was trying to use the msgpack serialization feature with discriminators

What I Did

from dataclasses import KW_ONLY, dataclass, field
from typing import Annotated, Literal

from mashumaro.mixins.msgpack import DataClassMessagePackMixin
from mashumaro.types import Discriminator


@dataclass
class A(DataClassMessagePackMixin):
    _: KW_ONLY
    t: str


@dataclass
class B(A):
    b: list[int]
    _: KW_ONLY
    t: Literal["b"] = "b"

@dataclass
class C(A):
    c: list[int]
    _: KW_ONLY
    t: Literal["c"] = "c"


assert B(b=[]).to_dict() == {"t": "b", "b": []}, B().to_dict()
assert B(b=[1, 2, 3]) == B.from_msgpack(B(b=[1, 2, 3]).to_msgpack())


@dataclass
class Group(DataClassMessagePackMixin):
    group: list[Annotated[A, Discriminator(field="t", include_subtypes=True)]]


assert B(b=[1, 2, 3]) == B.from_msgpack(B(b=[1, 2, 3]).to_msgpack())


g = Group([B(b=[1, 2, 3])])
assert Group.from_dict(g.to_dict()) == g
print(g.to_msgpack())
g2 = Group.from_msgpack(g.to_msgpack())
assert g2 == g, (g2, g)

crashes with:

mashumaro.exceptions.InvalidFieldValue: Field "group" of type list[A] in Group has invalid value [{'t': 'b'}]

because to_msgpack excludes the subtype data:

b'\x81\xa5group\x91\x81\xa1t\xa1b'

using:

@dataclass
class Group(DataClassMessagePackMixin):
    group: list[Annotated[B | C, Discriminator(field="t", include_supertypes=True)]]

works though

@Fatal1ty Fatal1ty added the bug Something isn't working label Jun 26, 2024
@Fatal1ty
Copy link
Owner

Discriminator is not used on serialization since its purpose is only to select a dataclass on deserialization. However, you are faced with using a parent class serialization issue from #225. I will close this issue as a duplicate, so feel free to subscribe to the related one.

@Fatal1ty Fatal1ty closed this as not planned Won't fix, can't repro, duplicate, stale Jun 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants