ordering with duck typing in 3.1
John O'Hagan
research at johnohagan.com
Sat Apr 7 10:40:51 EDT 2012
On Sat, 7 Apr 2012 05:23:25 -0700 (PDT)
andrew cooke <andrew at acooke.org> wrote:
>
> hi,
>
> please, what am i doing wrong here? the docs say
> http://docs.python.org/release/3.1.3/library/stdtypes.html#comparisons "in
> general, __lt__() and __eq__() are sufficient, if you want the conventional
> meanings of the comparison operators" but i am seeing
>
> > assert 2 < three
> E TypeError: unorderable types: int() < IntVar()
>
> with this test:
>
>
> class IntVar(object):
>
> def __init__(self, value=None):
> if value is not None: value = int(value)
> self.value = value
>
> def setter(self):
> def wrapper(stream_in, thunk):
> self.value = thunk()
> return self.value
> return wrapper
>
> 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
>
> so what am i missing?
>
I think that quote from the docs is just to point out that you only need those
two (== and <) to derive any of the other comparisons; but not to imply that a
class that only defines those two will automatically possess the others.
However, you can do that, with functools.total_ordering.
Regards,
John
More information about the Python-list
mailing list