Why keep identity-based equality comparison?

Mike Meyer mwm at mired.org
Sat Jan 14 17:17:52 EST 2006

Noam Raphael <spam.noam at gmail.com> writes:
>>>Also note that using the current behaviour, you can't easily
>>>treat objects that do define a meaningful value comparison, by
>> Yes you can. Just use the "is" operator.
> Sorry, I wasn't clear enough. In "treating" I meant how containers
> treat the objects they contain. For example, you can't easily map a
> value to a specific instance of a list - dict only lets you map a
> value to a specific *value* of a list.

Wrong. All you have to do is create a list type that uses identity
instead of value for equality testing. This is easier than mapping an
exception to false.

> Another example - you can't
> search for a specific list object in another list.

Your proposed == behavior doesn't change that at all.

>> I will point out why your example usages aren't really usefull if
>> you'll repeat your post with newlines.
> Here they are:
> * Things like "Decimal(3.0) == 3.0" will make more sense (raise an
> exception which explains that decimals should not be compared to
> floats, instead of returning False).

While I agree that Decimal(3.0) == 3.0 returning false doesn't make
sense, having it raise an exception doesn't make any more sense. This
should be fixed, but changing == doesn't fix it.

> * You won't be able to use objects as keys, expecting them to be
> compared by value, and causing a bug when they don't. I recently wrote
> a sort-of OCR program, which contains a mapping from a numarray array
> of bits to a character (the array is the pixel-image of the char).
> Everything seemed to work, but the program didn't recognize any
> characters. I discovered that the reason was that arrays are hashed
> according to their identity, which is a thing I had to guess. If
> default == operator were not defined, I would simply get a TypeError
> immediately.

This isn't a use case. You don't get correct code with either version
of '=='. While there is some merit to doing things that make errors
easier to find, Python in general rejects the idea of adding
boilerplate to do so. Your proposal would generate lots of boilerplate
for many practical situations.

> * It is more forward compatible - when it is discovered that two types
> can sensibly be compared, the comparison can be defined, without
> changing an existing behaviour which doesn't raise an exception.

Sorry, but that doesn't fly. If you have code that relies on the
exception being raised when two types are compared, changing it to
suddenly return a boolean will break that code.

Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list