Skip to content

Handle Optional unions in the tagged union strategy - #828

Closed
Aschenbath wants to merge 1 commit into
python-attrs:mainfrom
Aschenbath:fix-345-tagged-union-optional
Closed

Aschenbath wants to merge 1 commit into
python-attrs:mainfrom
Aschenbath:fix-345-tagged-union-optional

Conversation

@Aschenbath

Copy link
Copy Markdown

Fixes #345.

configure_tagged_union(Foo | Bar, converter) only registered hooks for the exact union, so a field typed Foo | Bar | None fell back to the default union handling: unstructuring dropped the _type tag, and structuring could not disambiguate (it even failed for None).

The strategy now also registers hooks for the union extended with None. Those hooks pass None through untouched and delegate everything else to the tagged union hooks, so both spellings work (Union[Foo, Bar, None] and Optional[Union[Foo, Bar]]), including when a default member is configured.

Tests:

  • Added test_optional_union and test_optional_union_in_class to tests/strategies/test_tagged_unions.py, covering direct union use and both field spellings, in both directions, including None.
  • Full tests/strategies/ suite: 276 passed, 15 xfailed.
  • ruff check and ruff format --check on the changed files: pass.

A changelog entry is included in HISTORY.md, and the strategy docstring documents the new behavior.

@Aschenbath

Copy link
Copy Markdown
Author

Closing this one myself: I opened too many PRs here in a short time, which isn't fair to your review queue — sorry about that. I'm leaving #827 and #822 open. If this fix is something you'd want, I'm happy to reopen or rebase it later.

@Aschenbath Aschenbath closed this Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can't use disambiguation strategy together with Optional

1 participant