comparing datetime with date

Tim Peters tim.peters at gmail.com
Wed Sep 15 14:14:31 EDT 2004


[Alex Martelli, on comparing datetime to date objects]
> I have no opinion on the specific semantics so I prefer to look at the
> logic of this... if we allow a date to compare equal to many different
> datetimes, then we have a situation in which:
>
> a == b
>
> AND
>
> a == c
>
> BUT NOT
> 
> b == c
>
> !!!
> (just pick a as a date, b and c as two different datetimes within
> it...).
>
> This means == does not define an equivalence relationship, and THAT is
> enough to send me into shivers and cold sweating.  Either having a
> comparison between date and datetime raise an exception, or consider a
> date to be == to ONE specific datetime, will be OK from this POV.  As
> for which choice is better, if I was the one tasked to design this, I'd
> go for "In the face of ambiguity, refuse the temptation to guess", and
> raise an exception.  But I don't feel particularly strongly about this.

The twist here is that datetime derives from date, and an object of a
class C usually thinks it's OK to compare itself with an object of a C
subclass.  Sometimes that's appropriate, sometimes not.  I agree it's
inappropriate in this case.

I expect that datetime_richcompare() needs to a grow a wart refusing
to allow delegation to date_richcompare() when "the other" argument is
not an instance of datetime but is an instance of date (BTW,
datetime_richcompare() does get first crack at doing the comparison,
because some hairy runtime code gives first crack to the object of the
more specific class when there's a subtype relationship between the
comparands' classes).



More information about the Python-list mailing list