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

Nested tagged unions? #708

Open
uar316025 opened this issue Jul 10, 2024 · 0 comments
Open

Nested tagged unions? #708

uar316025 opened this issue Jul 10, 2024 · 0 comments

Comments

@uar316025
Copy link

Question

Hi!
Can i do something like that?
(not sure how to name it)
Here example with pydantiic (v2)

First tagged union by type field
Then second by sub_type field

from typing import Literal, Annotated

import pydantic

class Device(pydantic.BaseModel):
    type: int
    sub_type: int
    name: str

class BlenderM1(Device):
    type: Literal[0x01] = 0x01
    sub_type: Literal[0x01] = 0x01

class BlenderM2(BlenderM1):
    sub_type: Literal[0x02] = 0x02

class OvenM1(Device):
    type: Literal[0x02] = 0x02
    sub_type: Literal[0x01] = 0x01

class OvenM2(OvenM1):
    sub_type: Literal[0x02] = 0x02

AnyDevice = Annotated[
    Annotated[BlenderM1 | BlenderM2, pydantic.Field(discriminator='sub_type')] |
    Annotated[OvenM1 | OvenM2, pydantic.Field(discriminator='sub_type')],
    pydantic.Field(discriminator='type')
]
print(pydantic.TypeAdapter(list[AnyDevice]).validate_python([
    {'type': 0x01, 'sub_type': 0x01, 'name': 'BM1'},
    {'type': 0x01, 'sub_type': 0x02, 'name': 'BM2'},
    {'type': 0x02, 'sub_type': 0x01, 'name': 'OM1'},
    {'type': 0x02, 'sub_type': 0x02, 'name': 'OM2'},
]))

which prints

[
  BlenderM1(type=1, sub_type=1, name='BM1'),
  BlenderM2(type=1, sub_type=2, name='BM2'),
  OvenM1(type=2, sub_type=1, name='OM1'),
  OvenM2(type=2, sub_type=2, name='OM2')
]

Also i can't change the devices structure because it is defined externally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant