[issue10042] functools.total_ordering fails to handle NotImplemented correctly

Nick Coghlan report at bugs.python.org
Mon Jul 8 09:30:36 CEST 2013


Nick Coghlan added the comment:

As part of this, I finally reviewed Jim's proposed alternate implementations for the helper functions. Katie's patch used my version while I figured out the differences in behaviour :)

The key difference between them relates to the following different approaches to handling unknown types in __eq__:

@functools.total_ordering
class TotallyOrderedEqualsReturnsFalse:
   def __init__(self, value):
       self._value = value
   def __eq__(self, other):
       return isinstance(other, Weird) and self._value == other._value
   def __lt__(self, other):
       if not isinstance(other, Weird): return NotImplemented
       return self._value < other._value

@functools.total_ordering
class TotallyOrderedEqualsReturnsNotImplemented:
   def __init__(self, value):
       self._value = value
   def __eq__(self, other):
       if not isinstance(other, Weird): return NotImplemented
       return self._value == other._value
   def __lt__(self, other):
       if not isinstance(other, Weird): return NotImplemented
       return self._value < other._value

Formally, the version which returns False directly is incorrect - it should be returning NotImplemented, and letting Python take of converting two results of NotImplemented to an equality comparison result of False.

In practice, lots of types are written that way, so we need to preserve the current behaviour of not checking the equality operations if the ordered comparison isn't implemented, or we will inadvertently end up making "<=" or ">=" return an answer instead of raising TypeError.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue10042>
_______________________________________


More information about the Python-bugs-list mailing list