On Mon, Jan 25, 2010 at 15:30, Nick Coghlan <[email protected]> wrote:
> Ah, you mean the case where both classes implement the recipe, but know
> nothing about each other and hence both return NotImplemented from their
> root comparison?
Well, only one needs to return NotImplemented, actually.
> OK, that sounds like a plausible real world problem with the recipe, but
> I'm not sure how difficult it would be to fix.
I've failed. :-) I currently something like this instead:
class ComparableMixin(object):
def __lt__(self, other):
try:
return self.__cmp__(other) < 0
except TypeError:
return NotImplemented
def __le__(self, other):
try:
return self.__cmp__(other) <= 0
except TypeError:
return NotImplemented
def __gt__(self, other):
try:
return self.__cmp__(other) > 0
except TypeError:
return NotImplemented
def __ge__(self, other):
try:
return self.__cmp__(other) >= 0
except TypeError:
return NotImplemented
def __eq__(self, other):
try:
return self.__cmp__(other) == 0
except TypeError:
return NotImplemented
def __ne__(self, other):
try:
return self.__cmp__(other) != 0
except TypeError:
return NotImplemented
That does rely on a (deprecated) __cmp__ but it will never be called
directly anyway.
The __cmp__ is then implemented something like this:
def __cmp__(self, other):
try:
return (self.v > other.v) - (self.v < other.v)
except AttributeError:
raise TypeError('Can not compare %s and %s' %
(type(self), type(other))
Since this doesn't "redirect" any of the __xx__ methods to another
one, the problem goes away.
But it uses a lot of annoying try/excepts. Ideas for improvements would be nice.
--
Lennart Regebro: http://regebro.wordpress.com/
Python 3 Porting: http://python-incompatibility.googlecode.com/
+33 661 58 14 64
_______________________________________________
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com