ordering with duck typing in 3.1
Rob Williscroft
rtw at rtw.me.uk
Sat Apr 7 10:37:17 EDT 2012
andrew cooke wrote in
news:33019705.1873.1333801405463.JavaMail.geo-discussion-forums at ynmm9 in
gmane.comp.python.general:
>
> 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 __lt__(self, other):
> return self.value < other
>
> so what am i missing?
>
The part of the docs you are relying on uses the wording "in general",
IOW, it is not saying that defining __eq__ and __lt__ will always be
sufficient.
In this case the expression "2 < three" is calling int.__lt__, which
doesn't know how to comapre to an instance of your class so returns
NotImplemented.
At this point if you had defined a __gt__ method the interpreter would then
try and call that having first switched the arguments around. But you
didn't so a TypeError is raised.
I'm afraid I couldn't find anywhere in the docs where that behaviour is
described, I suspect I only know it from lurking on usenet for a number of
years.
The best description that I could find of the behaviour you are seeing is
at:
http://docs.python.org/py3k/reference/expressions.html#not-in
There is a paragraph that contains:
"... the == and != operators always consider objects of different types to
be unequal, while the <, >, >= and <= operators raise a TypeError when
comparing objects of different types that do not implement these operators
for the given pair of types. ..."
Perhapse the docs could be reworded to note that, to define a full set of
comparisons between *different* types, you need to define a full set of
special methods.
Some links I found along the way:
http://docs.python.org/release/3.1.3/library/constants.html?
highlight=__lt__#NotImplemented
http://code.activestate.com/recipes/576685/
http://docs.python.org/py3k/library/functools.html#functools.total_ordering
Rob.
More information about the Python-list
mailing list