[Python-Dev] == on object tests identity in 3.x

Andreas Maier andreas.r.maier at gmx.de
Mon Jul 7 18:11:07 CEST 2014

Am 07.07.2014 17:58, schrieb Xavier Morel:
> On 2014-07-07, at 13:22 , Andreas Maier <andreas.r.maier at gmx.de> wrote:
>> While discussing Python issue #12067 (http://bugs.python.org/issue12067#msg222442), I learned that Python 3.4 implements '==' and '!=' on the object type such that if no special equality test operations are implemented in derived classes, there is a default implementation that tests for identity (as opposed to equality of the values).
>> The relevant code is in function do_richcompare() in Objects/object.c.
>> IMHO, that default implementation contradicts the definition that '==' and '!=' test for equality of the values of an object.
>> Python 2.x does not seem to have such a default implementation; == and != raise an exception if attempted on objects that don't implement equality in derived classes.
> That's incorrect on two levels:
> 1. What Terry notes in the bug comments is that because all Python 3
>     types inherit from object this can be done as a default __eq__/__ne__,
>     in Python 2 the fallback is encoded in the comparison framework
>     (PyObject_Compare and friends):
>     http://hg.python.org/cpython/file/01ec8bb7187f/Objects/object.c#l756
> 2. Unless comparison methods are overloaded and throw an error it will
>     always return either True or False (for comparison operator), never throw.

I was incorrect for Python 2.x.

>> I'd like to gather comments on this issue, specifically:
>> -> Can someone please elaborate what the reason for that is?
>> -> Where is the discrepancy between the documentation of == and its default implementation on object documented?
>> To me, a sensible default implementation for == on object would be (in Python):
>>   if v is w:
>>     return True;
>>   elif type(v) != type(w):
>>     return False
>>   else:
>>     raise ValueError("Equality cannot be determined in default implementation")
> Why would comparing two objects of different types return False

Because I think (but I'm not sure) that the type should play a role for 
comparison of values. But maybe that does not embrace duck typing 
sufficiently, and the type should be ignored by default for comparing 
object values.

 > but comparing two objects of the same type raise an error?

That I'm sure of: Because the default implementation (after having 
exhausted all possibilities of calling __eq__ and friends) has no way to 
find out whether the values(!!) of the objects are equal.


More information about the Python-Dev mailing list