cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

Support tagged unions when the discriminator field is in a generic wrapper, not in the union type

Open lukasK9999 opened this issue 6 months ago • 1 comments

Hello, I’m not sure if I just can’t figure out how to do it or if it’s not supported.

I have a generic message envelope like this:

@frozen
class KafkaMessage(Generic[T]):
    type: str  # discriminator
    payload: T

And payload can be one of several types:

@frozen
class Data: ...
@frozen
class Heartbeat: ...

I’d like to define and structure:

type KafkaMessageUnion = KafkaMessage[Data] | KafkaMessage[Heartbeat]
configure_tagged_union(KafkaMessageUnion, CONVERTER, tag_name="type")

however this fails on very first line of configure_tagged_union - args = union.__args__

Is it possible to get around this somehow?

lukasK9999 avatar May 26 '25 13:05 lukasK9999

Howdy.

I fixed this just recently: https://github.com/python-attrs/cattrs/pull/649

This issue is that the object created by the type statement isn't a union but a type alias. You can pass KafkaMessageUnion.__value__.

I plan on cutting a release on Friday, so then it should just work ;)

Tinche avatar May 27 '25 08:05 Tinche