Steven D'Aprano wrote: > I'm writing a class that implements rich comparisons, and I find myself > writing a lot of very similar code. If the calculation is short and > simple, I do something like this: > > > class Parrot: > def __eq__(self, other): > return self.plumage() == other.plumage() > def __ne__(self, other): > return self.plumage() != other.plumage() > def __lt__(self, other): > return self.plumage() < other.plumage() > def __gt__(self, other): > return self.plumage() > other.plumage() > def __le__(self, other): > return self.plumage() <= other.plumage() > def __ge__(self, other): > return self.plumage() >= other.plumage() > > If the comparison requires a lot of work, I'll do something like this: > > class Aardvark: > def __le__(self, other): > return lots_of_work(self, other) > def __gt__(self, other): > return not self <= other > # etc. > > But I can't help feeling that there is a better way. What do others do?
Once upon a time I had written a metaclass to generate the boilerate, filling in the gaps. It doesn't impose any constraints on which comparisons you must implement, e.g you may implement __le__ and __eq__, or __gt__ and __ne__, etc. Season to taste. http://rafb.net/p/mpvsIQ37.nln.html George -- http://mail.python.org/mailman/listinfo/python-list