Skip to content

gh-116647: Fix recursive child in dataclasses #116790

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

Merged
merged 7 commits into from Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__',
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2471,6 +2471,15 @@ def __repr__(self):


class TestEq(unittest.TestCase):
def test_recursive_eq(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the change! Per discussions in the issue, maybe also worth adding a test case for mutual recursive classes (given that's intended to be included in the scope of this PR)?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the comment, but I don't think mutual recursive classes can be implement with good performance, I've think ways like maintenance dict like id(obj) as key to check if it's recursive but it'll cost spaces and times to make compare like that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sense, thanks for the clarification!

# 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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix recursive child in dataclasses