Minimal duck type ordering methods in Python 3.1

The manual says:

in general, __lt__()and __eq__()are sufficient if you want conditional values ​​of comparison operators

But I see an error:

>       assert 2 < three
E       TypeError: unorderable types: int() < IntVar()

when i run this test:

from unittest import TestCase

class IntVar(object):

    def __init__(self, value=None):
        if value is not None: value = int(value)
        self.value = value

    def __int__(self):
        return self.value

    def __lt__(self, other):
        return self.value < other

    def __eq__(self, other):
        return self.value == other

    def __hash__(self):
        return hash(self.value)

class DynamicTest(TestCase):

    def test_lt(self):
        three = IntVar(3)
        assert three < 4
        assert 2 < three
        assert 3 == three

I am surprised that when IntVar()on the right, __int__()it is not called. What am I doing wrong?

Adding __gt__()fixes this, but means I don’t understand what the minimum requirements for ordering ...

Thanks Andrew

+5
source share
1 answer

Python 3.x will never do any type coercion for statements, so __int__()it is not used in this context. Comparison

a < b

type(a).__lt__(a, b), NotImplemented, type(b).__gt__(b, a).

, , , .

int, , total_ordering decorator Python 2.7 3.2.

+4

All Articles