-
Notifications
You must be signed in to change notification settings - Fork 118
Description
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