Skip to content

Commit c6b3106

Browse files
tirkarthimiss-islington
authored andcommitted
[3.7] bpo-37579: Improve equality behavior for pure Python datetime and time (GH-14726) (GH-14745)
Returns NotImplemented for timedelta and time in __eq__ for different types in Python implementation, which matches the C implementation. This also adds tests to enforce that these objects will fall back to the right hand side's __eq__ and/or __ne__ implementation. [bpo-37579](https://bugs.python.org/issue37579) (cherry picked from commit e6b46aa) Co-authored-by: Xtreak <tir.karthi@gmail.com> https://bugs.python.org/issue37579
1 parent 5631e38 commit c6b3106

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

Lib/datetime.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -718,7 +718,7 @@ def __eq__(self, other):
718718
if isinstance(other, timedelta):
719719
return self._cmp(other) == 0
720720
else:
721-
return False
721+
return NotImplemented
722722

723723
def __le__(self, other):
724724
if isinstance(other, timedelta):
@@ -1261,7 +1261,7 @@ def __eq__(self, other):
12611261
if isinstance(other, time):
12621262
return self._cmp(other, allow_mixed=True) == 0
12631263
else:
1264-
return False
1264+
return NotImplemented
12651265

12661266
def __le__(self, other):
12671267
if isinstance(other, time):

Lib/test/datetimetester.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,19 @@
5353
INF = float("inf")
5454
NAN = float("nan")
5555

56+
57+
class ComparesEqualClass(object):
58+
"""
59+
A class that is always equal to whatever you compare it to.
60+
"""
61+
62+
def __eq__(self, other):
63+
return True
64+
65+
def __ne__(self, other):
66+
return False
67+
68+
5669
#############################################################################
5770
# module tests
5871

@@ -399,6 +412,13 @@ def test_harmless_mixed_comparison(self):
399412
self.assertIn(me, [1, 20, [], me])
400413
self.assertIn([], [me, 1, 20, []])
401414

415+
# Comparison to objects of unsupported types should return
416+
# NotImplemented which falls back to the right hand side's __eq__
417+
# method. In this case, ComparesEqualClass.__eq__ always returns True.
418+
# ComparesEqualClass.__ne__ always returns False.
419+
self.assertTrue(me == ComparesEqualClass())
420+
self.assertFalse(me != ComparesEqualClass())
421+
402422
def test_harmful_mixed_comparison(self):
403423
me = self.theclass(1, 1, 1)
404424

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Return :exc:`NotImplemented` in Python implementation of ``__eq__`` for
2+
:class:`~datetime.timedelta` and :class:`~datetime.time` when the other
3+
object being compared is not of the same type to match C implementation.
4+
Patch by Karthikeyan Singaravelan.

0 commit comments

Comments
 (0)