Skip to content

Default union disambiguation function doesn't work with renamed keys #265

Open
@130ndim

Description

@130ndim
  • cattrs version: cattrs version: 22.1.0
  • Python version: 3.10
  • Operating System: MacOS Monterey 12.2.1

Description

I tried to structure some data into the union type with keys renaming. It doesn't work because the default disambiguation function creator builds it based on non-overriden fields (link). I could write a proper disambiguator myself but I think it should work out-of-the-box.

What I Did

from attrs import define
import cattrs
from cattrs.gen import make_dict_structure_fn, override

@define
class A:
    a_field: int


@define
class B:
    another_field: int


c = cattrs.GenConverter()

c.register_structure_hook(A, make_dict_structure_fn(A, c, a_field=override(rename="aField")))
c.register_structure_hook(B, make_dict_structure_fn(B, c, another_field=override(rename="anotherField")))

print(c.structure({'aField': 1}, A))
# A(a_field=1)

print(c.structure({'anotherField': 1}, B))
# B(another_field=1)

print(c.structure({'anotherField': 1}, A | B))
# B(another_field=1)

print(c.structure({'aField': 1}, A | B))
# raises ClassValidationError: While structuring B (1 sub-exception)
# ClassValidationError('While structuring B', [KeyError('another_field')])

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions