fix comparison of dataclasses with `InitVar`

This commit is contained in:
Anthony Sottile 2022-04-08 17:00:31 -04:00
parent 539a5d70f2
commit 8fa775bcee
4 changed files with 24 additions and 2 deletions

View File

@ -0,0 +1 @@
Fix comparison of ``dataclasses`` with ``InitVar``.

View File

@ -437,8 +437,10 @@ def _compare_eq_cls(left: Any, right: Any, verbose: int) -> List[str]:
if not has_default_eq(left):
return []
if isdatacls(left):
all_fields = left.__dataclass_fields__
fields_to_check = [field for field, info in all_fields.items() if info.compare]
import dataclasses
all_fields = dataclasses.fields(left)
fields_to_check = [info.name for info in all_fields if info.compare]
elif isattrs(left):
all_fields = left.__attrs_attrs__
fields_to_check = [field.name for field in all_fields if getattr(field, "eq")]

View File

@ -0,0 +1,12 @@
from dataclasses import dataclass
from dataclasses import InitVar
@dataclass
class Foo:
init_only: InitVar[int]
real_attr: int
def test_demonstrate():
assert Foo(1, 2) == Foo(1, 3)

View File

@ -882,6 +882,13 @@ class TestAssert_reprcompare_dataclass:
result.assert_outcomes(failed=1, passed=0)
result.stdout.no_re_match_line(".*Differing attributes.*")
def test_data_classes_with_initvar(self, pytester: Pytester) -> None:
p = pytester.copy_example("dataclasses/test_compare_initvar.py")
# issue 9820
result = pytester.runpytest(p, "-vv")
result.assert_outcomes(failed=1, passed=0)
result.stdout.no_re_match_line(".*AttributeError.*")
class TestAssert_reprcompare_attrsclass:
def test_attrs(self) -> None: