python-attrs / python-attrs/cattrs

Support subset of tagged union strategy

Open
#348 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Description

  • 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)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the configure_tagged_union entry point and reproduce the reported Foo and Bar examples with cattrs 23.1.0.dev0. Trace how configured tagged unions are matched and add coverage for a subset such as A | B; done means Bar(A(1)) uses the tagged-union strategy without requiring every combination to be configured.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.