python-attrs / python-attrs/cattrs

Can't use disambiguation strategy together with `Optional`

Open
#345 4 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

An optional tagged union doesn't work.

I believe the Optional (or | None) portion could be parsed beforehand, like it is on most fields, and the remaining type (Foo | Bar) then parsed separately, thus recognizing it as a tagged union.

What I Did
import attrs
import cattrs
from cattrs.strategies import configure_tagged_union


@attrs.define
class Foo:
    n: int = 42


@attrs.define
class Bar:
    n: int = 0


@attrs.define
class Baz:
    c: Foo | Bar


@attrs.define
class BazNone:
    c: Foo | Bar | None  # Could also have `= None` as a default value


converter = cattrs.Converter()
configure_tagged_union(Foo | Bar, converter=converter)
print(converter.unstructure(Baz(Bar(123))))  # {'c': {'n': 123, '_type': 'Bar'}}
print(converter.unstructure(BazNone(Bar(123))))  # {'c': {'n': 123}}

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 by reproducing the example with configure_tagged_union and the BazNone annotation, then inspect the tagged-union handling around that entry point. Done means an Optional or | None wrapper still uses the configured Foo | Bar disambiguation and preserves the tagged output shown for Baz.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.