]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-116647: Fix recursive child in dataclasses (#116790)
authoret-repositories <142979605+et-repositories@users.noreply.github.com>
Tue, 19 Mar 2024 14:58:40 +0000 (22:58 +0800)
committerGitHub <noreply@github.com>
Tue, 19 Mar 2024 14:58:40 +0000 (08:58 -0600)
Lib/dataclasses.py
Lib/test/test_dataclasses/__init__.py
Misc/NEWS.d/next/Library/2024-03-14-09-38-51.gh-issue-116647.h0d_zj.rst [new file with mode: 0644]

index e511eff4125038194317650c60924ef591df1b9d..7db8a4233df8836fd6a920458674ff9c81c4800d 100644 (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__',
index e27abac511139429e4a3d49166e1d4dbb6250096..832e5672c77d0dab65819e85596648a2092d7160 100644 (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)
diff --git a/Misc/NEWS.d/next/Library/2024-03-14-09-38-51.gh-issue-116647.h0d_zj.rst b/Misc/NEWS.d/next/Library/2024-03-14-09-38-51.gh-issue-116647.h0d_zj.rst
new file mode 100644 (file)
index 0000000..081f36b
--- /dev/null
@@ -0,0 +1 @@
+Fix recursive child in dataclasses