Boilerplate in rich comparison methods

Antoon Pardon apardon at forel.vub.ac.be
Mon Jan 15 10:55:59 CET 2007


On 2007-01-13, Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> 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()

Well one thing you could do is write the following class:

Comparators = SomeEnumWith("eq, ne, lt, gt, ge, le, ge")

class GeneralComparator:
  def __eq__(self, other):
    return Comparators.eq in self.__compare__(self, other)
  def __ne__(self, other):
    return Comparators.ne in self.__compare__(self, other)
  def __lt__(self, other):
    return Comparators.lt in self.__compare__(self, other)
  def __le__(self, other):
    return Comparators.le in self.__compare__(self, other)
  def __gt__(self, other):
    return Comparators.gt in self.__compare__(self, other)
  def __ge__(self, other):
    return Comparators.ge in self.__compare__(self, other)


Then write your Parrot class as follows:

  class Parrot (GeneralComparator):
    def __compare__(self, other):
      return a set which defines which comparisons should return true.

-- 
Antoon Pardon



More information about the Python-list mailing list