Skip to content

Commit e6b46aa

Browse files
tirkarthipganssle
authored andcommitted
bpo-37579: Improve equality behavior for pure Python datetime and time (GH-14726)
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
1 parent 05f2d84 commit e6b46aa

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
@@ -733,7 +733,7 @@ def __eq__(self, other):
733733
if isinstance(other, timedelta):
734734
return self._cmp(other) == 0
735735
else:
736-
return False
736+
return NotImplemented
737737

738738
def __le__(self, other):
739739
if isinstance(other, timedelta):
@@ -1310,7 +1310,7 @@ def __eq__(self, other):
13101310
if isinstance(other, time):
13111311
return self._cmp(other, allow_mixed=True) == 0
13121312
else:
1313-
return False
1313+
return NotImplemented
13141314

13151315
def __le__(self, other):
13161316
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)