Skip to content

nested tagged unions enumeration #726

@toppk

Description

@toppk

Question

I've reviewed other issues related to tagged unions. But I just wanted to see if there is some magic I can use.

In using tagged unions, I kinda have parent objects represented the tag. But of course, when setting up the decoder I cannot just give the parent class, but I have to give a union (i get it). But that goes for the nested structs too. This example focuses on that.

if you look at Title2 vs Title below you'll see what I had to do, in order to get decode to work. Obviously encoding doesn't have such an issue.

I'd wish for example there would be some magic flag that you could tell the decoder to find the union structs on it's own, instead of having to specify it, and most importantly not being able change outer struct to specify a full union rather then the nested struct parent class (e.g. `Inner')

import msgspec

class Base(msgspec.Struct, tag_field='base'): ...

class Inner(msgspec.Struct, tag_field='inner'): ...

class Page(Inner, tag='page'):
    foo: str

class Box(Inner, tag='box'):
    foo: str

class Title(Base, tag='title'):
    item: Inner  # doesn't work

class Title2(Base, tag='title'):
    item: Page | Box # works

obj = Title(item=Page(foo='yes'))

print(msgspec.json.encode(obj).decode())

jstr = '{"base":"title","item":{"inner":"page","foo":"yes"}}'

decoder = msgspec.json.Decoder(Title2)
print (decoder.decode(jstr)) # works

decoder = msgspec.json.Decoder(Title)
print (decoder.decode(jstr)) # doesn't work

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