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

Ethan Furman ethan at stoneleaf.us
Tue Jul 8 01:50:57 CEST 2014

On 07/07/2014 04:36 PM, Andreas Maier wrote:
> Am 2014-07-07 19:43, schrieb Ethan Furman:
>> Python cannot know which values are important in an equality test, and which are not.  So it refuses to guess.
> Well, one could argue that using the address of an object for its value equality test is pretty close to guessing,
> considering that given a sensible definition of value equality, objects of different identity can very well be equal but
> will always be considered unequal based on the address.

And what would be this 'sensible definition'?

> So we have many cases of classes whose designers thought about whether a sensible definition of equality was needed, and
> decided that an address/identity-based equality definition was just what they needed, yet they did not want to or could
> not use the "is" operator?

1) The address of the object is irrelevant.  While that is what CPython uses, it is not what every Python uses.

2) The 'is' operator is specialized, and should only rarely be needed.  If equals is what you mean, use '=='.

3) If Python forced us to write our own __eq__ /for every single class/ what would happen?  Well, I suspect quite a few 
would make their own 'object' to inherit from, and would have the fallback of __eq__ meaning object identity. 
Practicality beats purity.

> Can you give me an example for such a class (besides type object)? (I.e. a class that does not have __eq__() and
> __ne__() but whose instances are compared with == or !=)

I never add __eq__ to my classes until I come upon a place where I need to check if two instances of those classes are 
'equal', for whatever I need equal to mean in that case.

>> Ordering is much less frequent, and since we already tried always ordering things, falling back to type name if
>> necessary, we have discovered that that is not a good trade-off.  So now if one tries to order things without
>> specifying how it should be done, one gets an exception.
> In Python 2, the default ordering implementation on type object uses the identity (address) as the basis for ordering.
> In Python 3, that was changed to raise an exception. That seems to be in sync with what you are saying.
> Maybe it would have been possible to also change that for the default equality implementation in Python 3. But it was
> not changed. As I wrote in another response, we now need to document this properly.

Doc patches are gratefully accepted.  :)


More information about the Python-Dev mailing list