[Python-ideas] Automatic comparisons by default

Guido van Rossum guido at python.org
Tue Mar 15 22:33:37 CET 2011


On Tue, Mar 15, 2011 at 12:27 PM, Facundo Batista
<facundobatista at gmail.com> wrote:
> On Tue, Mar 15, 2011 at 3:18 PM, Raymond Hettinger
> <raymond.hettinger at gmail.com> wrote:
>
>> It's a little more complicated than "if Python doesn't find ...".
>> In Python 3, object() already has __le,__, __gt__, __ge__, and __gt__,
>> so those methods always get found.
>
> I'm seeing that it also defines __eq__ and __ne__, but in this case we
> could make __ne__ to return NotImplemented, and automatically call
> "not __eq__()" (that for object() is the opposite).
>
>
>> You can use an identity check to see if those methods have been
>> overridden, but I think the only truly correct way to tell if one of the
>> rich comparison methods is defined is to call it and see whether
>> it returns NotImplemented.
>
> Not following... object.__lt__ raises TypeError, does not return NotImplemented.
>
> We could make object() to return NotImplemented for __le__ and __ge__,
> and in such case it would call "__eq__() or __lt__()" (returning True
> if the object is the same, or raising TypeError to prevent ordering
> the unorderable object)

By now it should be clear that this is a very complicated area. The
subtleties to consider include but are probably not limited to:

- what to do with object, which defines all six operations already

- relationship between < and >=: Facundo said in his first message
that "cmp" could be replaced by just <= and ==, but I do not believe
that always works (e.g. sets)

- relationship between <, <=, ==: is < defined in terms of <= and ==,
or is <= defined in terms of < and ==?

- what to do if the operands have different classes, e.g. what does a
<= b mean if a defines __lt__ and b defines __ge__ (not to mention
when one class is a subclass of the other)

- backwards compatibility

If someone still has any doubts let them try to implement this
proposal in CPython (3.3 branch please) and see how many tests fail.
(Or for that matter, try to implement it in PyPy -- although that
doesn't do Python 3 yet, so it's even more complicated.)

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list