Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
10 changes: 8 additions & 2 deletions Doc/library/dataclasses.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,16 @@ Module contents
ignored.

- *eq*: If true (the default), an :meth:`~object.__eq__` method will be
generated. This method compares the class as if it were a tuple
of its fields, in order. Both instances in the comparison must
generated.

.. versionchanged:: 3.13
The generated ``__eq__`` method now compares each field individually (e.g., ``self.a == other.a and self.b == other.b``), rather than comparing tuples of fields as in previous versions.
Copy link
Member

Choose a reason for hiding this comment

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

Please wrap lines to 79 characters.

Also, please don't use Latin abbreviations, see the devguide for more information.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks! I’ve made the updates based on your suggestions.


This method compares the class by comparing each field in order. Both instances in the comparison must
be of the identical type.

In Python 3.12 and earlier, the comparison was performed by creating tuples of the fields and comparing them (e.g., ``(self.a, self.b) == (other.a, other.b)``).

If the class already defines :meth:`!__eq__`, this parameter is
ignored.

Expand Down
39 changes: 39 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2597,6 +2597,45 @@ def __eq__(self, other):
self.assertEqual(C(1), 5)
self.assertNotEqual(C(1), 1)

def test_eq_field_by_field(self):
@dataclasses.dataclass
class Point:
x: int
y: int

p1 = Point(1, 2)
p2 = Point(1, 2)
p3 = Point(2, 1)
self.assertTrue(p1 == p2)
self.assertFalse(p1 == p3)

def test_eq_type_check(self):
@dataclasses.dataclass
class A:
x: int

@dataclasses.dataclass
class B:
x: int

a = A(1)
b = B(1)
self.assertFalse(a == b)

def test_eq_custom_field(self):
class AlwaysEqual(int):
def __eq__(self, other):
return True

@dataclasses.dataclass
class Foo:
x: AlwaysEqual
y: int

f1 = Foo(AlwaysEqual(1), 2)
f2 = Foo(AlwaysEqual(2), 2)
self.assertTrue(f1 == f2)


class TestOrdering(unittest.TestCase):
def test_functools_total_ordering(self):
Expand Down
Loading