For my Python 2.7.3 project I have a class called custom_date, which has a property called fixed_date:
from datetime import date
class custom_date():
def __init__(self, fixed_date):
self.fixed_date = fixed_date
def __lt__(self, other):
return self.fixed_date < other
#__gt__, __ge__, __le__, __eq__, __ne__ all implemented the same way
My idea is to be able to directly compare custom_date.fixed_date with the builtin date.
Problem
If I compare a custom_date object to a date object, it’s fine. However, if I compare a date object to a custom_date, it returns a TypeError
>>> from datetime import date
>>> x = custom_date(date(2013,2,1))
>>> y = date(2013,2,2)
>>> x > y
False
>>> y > x
TypeError: can't compare datetime.date to instance
Is there any way around this?
Just subclass
dateto get this functionality. Since a datetime object is immutable, you need to use the__new__constructor vs__init__:Prints:
Since the determinative class for comparisons is the LH class, the class on the left needs to have the correct comparison operators to deal with the comparison with the class on the right. If there are no comparison operators for either class, instances are sorted by identity — their memory address. Your error is essentially from trying to compare an apple to an orange: identity to a date class.
Note that there used to be a rcmp that was removed in Python 2.1 to deal with such issues. Introduction of the new style classes and rich comparisons have also led to
__cmp__being deprecated.