Skip to content

Honor renamed literal fields in union disambiguation - #778

Open
caamer20 wants to merge 1 commit into
python-attrs:mainfrom
caamer20:codex/fix-renamed-literal-discriminators
Open

caamer20 wants to merge 1 commit into
python-attrs:mainfrom
caamer20:codex/fix-renamed-literal-discriminators

Conversation

@caamer20

Copy link
Copy Markdown

Problem

A union whose literal discriminator is renamed with override(rename=...) cannot read back its serialized output. For example, after configuring kind to serialize as type, {'type': 'cat'} fails with KeyError: 'kind' when structured as Cat | Dog. The unique-field discriminator already honors renaming, but the literal discriminator still uses the Python attribute name.

Change

Build the literal candidates by serialized name using the existing _overriden_name helper, retaining the attribute objects to read their literal values. This handles both different attributes renamed to a common discriminator and a common attribute renamed to different keys; the latter falls back to unique-field disambiguation. An empty-string rename is also treated as a valid key.

Includes an API version note and changelog entry. The regression tests cover attrs classes, dataclasses, both converter implementations, both validation modes, overrides discovered from hooks, and explicit overrides. All 25 new cases fail on the original implementation.

Validation

On Python 3.14.7:

  • python -m pytest -q -n 4 tests: 1,019 passed, 15 expected failures.
  • ruff check src/ tests bench: passed.
  • ruff format --check src tests docs/conf.py: passed (115 files).
  • Ruff uses version 0.15.6 from uv.lock.
  • git diff --check: passed.
  • Sphinx doctests: 253 examples passed. HTML and doctest builds with -W report the same existing Unknown target name: "factory" warning in defaultdict_structure_factory; the HTML warning was reproduced from a pristine upstream checkout. Sphinx 8.2.3, MyST 4.0.1, and Docutils 0.21.2 match uv.lock.

Developed with Codex assistance; the reproduction and validation above were run locally.

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.

1 participant