How to handle mixed types when implementing comparison operators?

What is the most natural way to execute the following code?

import functools

@functools.total_ordering
class X:
    def __init__(self, a):
        self._a = a

    def __eq__(self, other):
        if not isinstance(other, X):
            return False
        return self._a == other._a

    def __lt__(self, other):
        if not isinstance(other, X):
            return ...                    // what should go here?
        return self._a < other._a

if __name__ == '__main__':
    s = [2, 'foo', X(2)]
    s.sort()
    print s
+5
source share
2 answers

You can choose what seems natural to you; Falsemeans your instances are always sorted after the other types True, and they will be sorted sooner.

Alternatively, you can return NotImplemented(see __lt__other documents of comparison methods ) to signal that comparison is not supported:

def __lt__(self, other):
    if not isinstance(other, X):
        return NotImplemented
    return self._a < other._a

Indication of documentation:

singleton NotImplemented, . False True. , , (, if), Python bool() , , .

+2

:

.

.

: ( , )

, , :

http://docs.python.org/library/stdtypes.html#comparisons

, , ; , ( ). , (, ) , . , , . <, < =, > >= TypeError, .

, ... , , .

- - .

+4

All Articles