__cmp__ between dissimilar objects

Gabriel Genellina gagsl-py at yahoo.com.ar
Mon Nov 13 21:29:36 EST 2006


At Monday 13/11/2006 21:33, insyte at gmail.com wrote:

>I have a class that has, as an attribute, an instance of
>datetime.datetime().  I would like to be able to compare my class
>directly to instances of datetime.datetime in addition to other
>instances of my class.  The value used for the comparison in either
>case should be the value of the datetime attribute of the class:
>
>from datetime import datetime
>
>class GeneralizedTime(object):
>     def __init__(self, time=None):
>         if time is None:
>             self.datetime = datetime.now()
>     def __cmp__(self, x):
>         if isinstance(x, GeneralizedTime):
>             return cmp(self.datetime, x.datetime)
>         if isinstance(x, datetime):
>             return cmp(self.datetime, x)
>
>
> >>> import datetime
> >>>
> >>> GeneralizedTime() > datetime.now()
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>TypeError: can't compare datetime.datetime to GeneralizedTime

This appears to be some braindead code in the datetime class.
You have to provide all the "rich-comparison" methods, and even then, 
will never work when a datetime instance is at the left of the comparison.

     def __lt__(self, other): return self.__cmp__(other)<0
     def __le__(self, other): return self.__cmp__(other)<=0
     def __gt__(self, other): return self.__cmp__(other)>0
     def __ge__(self, other): return self.__cmp__(other)>=0
     def __eq__(self, other): return self.__cmp__(other)==0
     def __ne__(self, other): return self.__cmp__(other)!=0

When the rich comparison methods raise NotImplementedError, the 
comparison logic inside the interpreter tries reversing the operands. 
But datetime objects don't do that, they raise TypeError, thus 
preventing the operand reversing. So any comparison with datetime on 
the left and your GeneralizedTime on the right side will fail.
If nobody has an explanation on *why* datetime does this, I'd say it's a bug.


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list