Python 3 __cmp__ semantic change?

Arnaud Delobelle arnodel at googlemail.com
Sat Nov 22 05:57:00 EST 2008


Arnaud Delobelle <arnodel at googlemail.com> writes:

> I haven't done any tests but as Fraction.__gt__ calls *both*
> Fraction.__eq__ and Fraction.__lt__ it is obvious that it is going to be
> roughly twice as slow.

There's a very simple way of emulating Fraction.__cmp__ in Python 3:

def totally_ordered(cls):
    def __lt__(self, other): return self.cmp(other) < 0
    def __eq__(self, other): return self.cmp(other) == 0
    def __gt__(self, other): return self.cmp(other) > 0
    cls.__lt__ = __lt__
    cls.__eq__ = __eq__
    cls.__gt__ = __gt__
    # and same with __le__, __ge__
    return cls

@totally_ordered
class Fraction:
    def __init__(self, num, den=1):
        assert den > 0, "denomintator must be > 0"
        self.num = num
        self.den = den
    def cmp(self, other):
        return self.num*other.den - self.den*other.num


It doesn't suffer the speed penalty incurred when defining comparison
operators from __eq__ and __lt__.

-- 
Arnaud



More information about the Python-list mailing list