gh-116647: Fix recursive child in dataclasses (#116790)

This commit is contained in:
et-repositories 2024-03-19 22:58:40 +08:00 committed by GitHub
parent 3cac2af5ec
commit 75935746be
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 13 additions and 1 deletions

View File

@ -1075,7 +1075,9 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
cmp_fields = (field for field in field_list if field.compare)
terms = [f'self.{field.name}==other.{field.name}' for field in cmp_fields]
field_comparisons = ' and '.join(terms) or 'True'
body = [f'if other.__class__ is self.__class__:',
body = [f'if self is other:',
f' return True',
f'if other.__class__ is self.__class__:',
f' return {field_comparisons}',
f'return NotImplemented']
func = _create_fn('__eq__',

View File

@ -2471,6 +2471,15 @@ class TestRepr(unittest.TestCase):
class TestEq(unittest.TestCase):
def test_recursive_eq(self):
# Test a class with recursive child
@dataclass
class C:
recursive: object = ...
c = C()
c.recursive = c
self.assertEqual(c, c)
def test_no_eq(self):
# Test a class with no __eq__ and eq=False.
@dataclass(eq=False)

View File

@ -0,0 +1 @@
Fix recursive child in dataclasses