Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
130ndim opened this issue May 3, 2022 · 1 comment
Open

Comments

@130ndim
Copy link

130ndim commented May 3, 2022

  • 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')])
@rminderhoud
Copy link

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.

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

No branches or pull requests

2 participants