Boilerplate in rich comparison methods

Duncan Booth duncan.booth at invalid.invalid
Sat Jan 13 11:22:24 EST 2007


"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote:

> In Python, this would look like:
> 
> class Parrot:
>     def __eq__(self, other):
>         return self is other or self.plumage() == other.plumage()
>     def __ne__(self, other):
>         return self is not other and self.plumage() != other.plumage()
>     def __lt__(self, other):
>         return self is not other and self.plumage() < other.plumage()
>     def __gt__(self, other):
>         return self is not other and self.plumage() > other.plumage()
>     def __le__(self, other):
>         return self is not other and self.plumage() <= other.plumage()
>     def __ge__(self, other):
>         return self is not other and self.plumage() >= other.plumage()
> 
> and George's metaclass would have similar changes.
> 
> On the other hand, I haven't seen this idiom in any Python code that
> I've read, and I wonder if this was just a coding fad of the time.

It is a perfectly reasonable short-cut for those types where you know an 
object is equal to itself, but that isn't always the case. e.g. floating 
point NaN values are not equal to themselves, and a list of numbers might 
contain a NaN which would mean the list wouldn't be equal to itself.

Also note that for the __le__, __ge__ cases you got the shortcut test the 
wrong way round.



More information about the Python-list mailing list