The problem is that the comparison calls the __eq__ function, the opposite of what you are looking for. A __eq__ method works if you have ScheduleData() == datetime.date() , but the in operator performs the comparison in reverse order, datetime.date() == ScheduleData() , which does not call your specific __eq__ . Only the class acting as the left side will have its __eq__ .
The reason this problem occurs in python 2 rather than 3 is due to the definition of datetime.date.__eq__ in the std library. Take, for example, the following two classes:
class A(object): def __eq__(self, other): print ('A.__eq__') return False class B(object): def __eq__(self, other): print ('B.__eq__') items = [A()] B() in items
Running this code prints B.__eq__ under both Python 2 and Python 3. Object B used as lhs, just like your datetime.date object is used in Python 2. However, if I redefine B.__eq__ to resemble Python 3 defintion datetime.date.__eq__ :
class B(object): def __eq__(self, other): print ('First B.__eq__') if isinstance(self, other.__class__): print ('B.__eq__') return NotImplemented
Then:
First B.__eq__ A.__eq__
printed under both Python 2 and 3. Returning NotImplemented causes a check with the arguments changed.
Using timetuple in your class, this problem will be fixed, as pointed out by @TimPeters (an interesting workaround that I did not know about), although it seems that this should not be a function
class ScheduleData: timetuple = None
- thatβs all you need in addition to what you already have.
source share