cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

Default union disambiguation function doesn't work with renamed keys

Open 130ndim opened this issue 3 years ago • 1 comments

  • 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')])

130ndim avatar May 03 '22 12:05 130ndim

I just ran into this as well with the exact same use case. Using rename to convert from snake case to camel case and my union type gets incorrectly disambiguated.

rminderhoud avatar May 06 '22 00:05 rminderhoud