Skip to content

fix: match enum-valued Literal discriminators by their unstructured value - #840

Open
vanshbarfiwala-lgtm wants to merge 1 commit into
python-attrs:mainfrom
vanshbarfiwala-lgtm:fix/enum-literal-discriminator
Open

vanshbarfiwala-lgtm wants to merge 1 commit into
python-attrs:mainfrom
vanshbarfiwala-lgtm:fix/enum-literal-discriminator

Conversation

@vanshbarfiwala-lgtm

Copy link
Copy Markdown

Structuring a union of attrs classes discriminated by an enum-valued Literal crashes with KeyError, even though unstructuring the same union works. String- and integer-valued Literal discriminators work, so it is an asymmetric round-trip failure specific to enums.

from typing import Union, Literal
from enum import Enum
from attrs import define
from cattrs import Converter

c = Converter()

class Species(Enum):
    CAT = "cat"
    DOG = "dog"

@define
class ECat:
    kind: Literal[Species.CAT]
    meow: int = 1

@define
class EDog:
    kind: Literal[Species.DOG]
    woof: int = 2

u = c.unstructure(ECat(Species.CAT), unstructure_as=Union[ECat, EDog])  # {'kind': 'cat', 'meow': 1}
c.structure(u, Union[ECat, EDog])                                       # KeyError: 'cat'

Cause: in create_default_dis_func (src/cattrs/disambiguators.py), the value-to-class mapping is keyed by the raw Literal args, i.e. the enum members. The returned disambiguator then looks up the discriminator from the already-unstructured payload, where the member has been serialized to its value ('cat'), so the member keys never match. For str/int Literals the member and its serialized value are identical, which is why only enums break.

Fix: key the mapping by the unstructured value (converter.unstructure(key)). This is identity for str/int/bool (existing cases unchanged) and yields the enum's value for enum members, so lookups match the unstructured discriminator. Added a test and a HISTORY entry.

…alue

create_default_dis_func keyed the discriminator mapping by the raw Literal
args, but the disambiguator looks them up against the already-unstructured
input. For an enum-valued Literal the member is serialized to its value, so
the lookup raised KeyError (structure failed while unstructure succeeded).
Key the mapping by the unstructured value, which is identity for str/int/bool
and the member's value for enums.

This branch has not been deployed

No deployments
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