python 3's adoption

Paul Boddie paul at boddie.org.uk
Fri Jan 29 10:34:31 EST 2010


On 29 Jan, 06:56, Terry Reedy <tjre... at udel.edu> wrote:
> On 1/28/2010 6:47 PM, Paul Boddie wrote:
>
> > What would annoy me if I used Python 3.x would be the apparent lack of
> > the __cmp__ method for conveniently defining comparisons between
> > instances of my own classes. Having to define all the rich comparison
> > methods frequently isn't even as much fun as it sounds.
>
> You define __eq__, which automatically generates __ne__.

>From the Python 3.1 language reference:

"There are no implied relationships among the comparison operators.
The truth of x==y does not imply that x!=y is false. Accordingly, when
defining __eq__(), one should also define __ne__() so that the
operators will behave as expected."

Maybe Python 3.1 plugs a default method in, anyway.

> You define __lt__, which is all sort and heap need.
> This should be about as easier than __eq__, which is really needed, and
> __cmp__. If you need the other 3, either copy the recipe in the
> Cookbook, or, even faster
>
> def __ge__(s,o): return o.__lt__(s)
> def __le__(s,o): return s < o or s == o
> def __ge__(s,o): return s > o or s == o

Spot the error in the above. ;-) Of course, this could be defined in a
base class and be inherited everywhere, but the case that made me
raise this issue actually involved instances of a class delegating
comparison/sorting to another object. With __cmp__ this can be done
concisely and only involve the delegation of one method - not so with
the rich comparison "protocol".

Paul



More information about the Python-list mailing list