Incomparable abominations (was: python-dev Summary)
Tim Peters
tim.one at comcast.net
Sat Mar 22 23:44:24 EST 2003
[Donn Cave]
> What about
>
> 1 == "2"
>
> , should it also be cause for an exception? Sorry if I missed the
> earlier posts in this thread that would explain how == differs from
> < in this application.
It's arguable both ways, of course. After rich comparisons appeared, people
played with both approaches in their own types. What Guido seems happiest
with now (and which I not coincidentally implemented for the 2.3 datetime
module's types, after real-world problems with "always raise an exception"
on meaningless comparisons):
class SomeType:
def __eq__(self, other):
if not_a_type_i_know_about(type(other)):
return NotImplemented
return True or False appropriately
and similarly for __ne__. The others raise TypeError instead if they don't
know about other.
The implications for __eq__: if type(other) is not one SomeType knows
about, returning NotImplemented gives other a chance at providing a
meaningful result. If other.__eq__(self) also returns NotImplemented,
Python falls back to comparing self and other by memory address. Since self
is not other, this must return False.
Similarly, if __ne__ falls back to comparing by memory address, that must
return True.
In a world where this was consistently applied,
1 == "2"
would return False, and
1 != "2"
True, and
1 <= "2"
1 < "2"
1 > "2"
1 >= "2"
would raise TypeError.
More information about the Python-list
mailing list