PyComparable: you probably don’t need it
2008-10-04 / 18:02 / dave
This thread tangentially brought up the fact that Python doesn’t automatically generate __ne__ (called by !=) from __eq__ (==).
Madness ensued.
In a libertarian spirit, I hacked out a class decorator to add rich comparison methods. Then I forgot all about it. Then I was bored on a plane flying back from Victoria. Now I present to you…
PyComparable
PyComparable is a Python package to add rich comparison methods to a class. The name is based on Ruby’s Comparable mixin, though it turns out to be a bad name. Ruby’s Comparable defines rich comparisons based on the <=> method, something Python already does. PyComparable is instead intended for when you have some rich comparison methods and want to generate the rest. (Of course, this hardly ever happens which is why you will probably never ever need PyComparable. Oh well.)
It’s also not really meant to be used as a mixin (though I provide ComparableMixin and ComparableMetaclass for your pleasure). Instead it’s a designed for future use as a class decorator: the comparable function takes a class as an argument, adds the methods, and returns a new class.
You can get more details in the README.
PS: It looks like this was done back in January 2007. Unfortunately, the link was dead.
PPS:
There’s also an ActiveState recipe that takes a slightly different approach. It assumes the objects being compared are “reflective” (I doubt that’s technically correct): it relies on reversing the operands. The upshot is that it only requires you to implement one comparison method. PyComparable requires two comparison methods, but never calls a method of the right hand side operand.
Oh, and there’s the fact that neither will work in Python 2.6 or 3. Doh!
