cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

Support subset of tagged union strategy

Open MicaelJarniac opened this issue 2 years ago • 0 comments

  • cattrs version: 23.1.0.dev0
  • Python version: 3.11.1
  • Operating System: Manjaro KDE

Description

Subsets of tagged unions should also be able to use the configured strategy.

What I Did

import attrs
import cattrs
from cattrs.strategies import configure_tagged_union


@attrs.define
class A:
    x: int


@attrs.define
class B:
    x: str


@attrs.define
class C:
    x: list[float]


@attrs.define
class Foo:
    y: A | B | C


@attrs.define
class Bar:
    y: A | B


c = cattrs.Converter()
configure_tagged_union(A | B | C, converter=c)
c.unstructure(Foo(A(1)))  # {'y': {'x': 1, '_type': 'A'}}
c.unstructure(Bar(A(1)))  # {'y': {'x': 1}}

Because Bar uses only A | B, and I've only configured A | B | C, it doesn't use the strategy. I think it should be possible to use the strategy for A | B | C when I only have A | B, a subset of it. If not by default, this should be a configurable option, like configure_tagged_union(A | B | C, converter=c, allow_subset=True).

Otherwise, I'd need to repeatedly define all possible combinations of A, B, and C, like:

configure_tagged_union(A | B, converter=c)
configure_tagged_union(A | C, converter=c)
configure_tagged_union(B | C, converter=c)
configure_tagged_union(A | B | C, converter=c)

MicaelJarniac avatar Apr 06 '23 13:04 MicaelJarniac