cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

disambiguators.create_uniq_field_dis_func fails to disambiguate ambiguous unions depending on parameter order

Open brakhane opened this issue 3 years ago • 0 comments

  • cattrs version: 1.10.0
  • Python version: 3.10.0
  • Operating System: Win

Description

In some cases, create_uniq_field_dis_func fails to disambiguate certain unions. The order of arguments matter, which can cause some confusion if eg. the arguments are taken from a set with no strict ordering, because it sometimes works, and sometimes fails.

Consider the following program:

import attrs, cattrs

# the fields are named after the classes they share
@attrs.define
class A:
    ab: int
    a: str

@attrs.define
class B:
    ab: int
    bc: int

@attrs.define
class C:
    bc: int

cattrs.disambiguators.create_uniq_field_dis_func(A, B, C)  # no error
cattrs.disambiguators.create_uniq_field_dis_func(B, A, C)  # ValueError: <class '__main__.B'> has no usable unique attributes.

Another case where this can bite people is if Union[A, B, C] was defined, and the code works, then later on, somebody defines Union[B, A, C] in a module that is executed earlier. Python will convert the types into whatever was defined first, so suddenly, Union[A, B, C] is treated like Union[B, A, C]

brakhane avatar Feb 15 '22 16:02 brakhane