Gaining more control over rich comparison operators in python2

>>> class Yeah(object): ... def __eq__(self, other): ... return True ... >>> class Nah(object): ... def __eq__(self, other): ... return False ... >>> y = Yeah() >>> n = Nah() >>> y == n True >>> n == y False 

The left guy wins because when python2 sees x == y , he first tries x.__eq__(y) .

Is there a way to change Nah so that he wins both times?

My use case does something like this:

 class EqualsAnyDatetime(object): def __eq__(self, other): return isinstance(other, datetime) 

It just works in python3 because real_datetime.__eq__(random_other_thing) raises NotImplemented , giving the other side a shot when comparing. In python2, I cannot get this idea to work.

+2
source share
2 answers

I found a way that can give the right side the opportunity to say "I am the first." The trick is to inherit from the type (s) you want to strengthen against comparison.

Example:

 >>> from datetime import datetime >>> class EqualsAnyDatetime(datetime): ... def __eq__(self, other): ... return isinstance(other, datetime) ... >>> now = datetime.now() >>> any_datetime = EqualsAnyDatetime(1970, 1, 1) >>> now == any_datetime True >>> any_datetime == now True >>> now.__eq__(any_datetime) False 
+1
source

No, you cannot do this. The left operand is always checked first. If it processes the operation, the right operand will never be able to do anything.

+1
source

Source: https://habr.com/ru/post/1273770/


All Articles