What is up with "=="?
Bengt Richter
bokr at oz.net
Thu Oct 9 20:24:26 EDT 2003
On Wed, 08 Oct 2003 14:29:08 -0700, Erik Max Francis <max at alcyone.com> wrote:
>Quentin Crain wrote:
>
>> 1 Whos __eq__ or __cmp__ is being called: String's or
>> Int's?
>> 2 Why IS comparison supported across types?
>> 3 The exception + gives makes it sound like there is
>> a built-in function + that does not like taking an
>> 'int' and a 'string'. Read this way, the built-in ==
>> does accept 'int' and 'string'.
>
>It's really a judgement call. It's certainly possible to set up an
>equality operator which respects type, but in a dynamic language like
>Python, you'll often find yourself comparing objects of different types
>for equality. This can get inconvenient, since this means that this
>comparisons would raise TypeErrors when all you really care about is
>whether or not they're equal or not. Two objects of different types are
>obviously unequal (unless __eq__ is deliberately overridden, etc.,
>etc.), so it makes sense to simply have == and != not raise TypeErrors.
>
>In fact, it's so common, that if your standard equality operator _does_
>raise TypeErrors, you're almost guaranteeing you need another builtin
>equality operator which does _not_ respect type. So now you have two
>equality operators, which can be confusing -- there's
>test-equality-and-raise-if-the-types-are-different and
>test-equality-and-treat-different-types-as-simply-unequal. This isn't
>necessarily the end of the world, but it's inconvenient. (For the
>record, I used this approach -- two equality operators, `eq' and `seq'
>-- so I'm not opposed to it on general principle.)
>
>Plus the dynamicism of Python itself enters into it. I can easily come
>up with custom classes, whether actually derived from numeric types or
>not, which I _do_ want to test equal to existing types. Now it's
>looking much more like it would be advantageous for equality to simply
>not raise an error on different types and just say, "Nope, they're not
>equal."
>
The OP might want to know about type difference NOT implying unequal when
conversion can be done, as between numbers. E.g.,
>>> 2==2.0, 2==2L, 2L==2.0
(True, True, True)
BTW, this looks like a bug in the doc<->reality relationship:
Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> help(coerce)
Help on built-in function coerce:
coerce(...)
coerce(x, y) -> None or (x1, y1)
When x and y can be coerced to values of the same type, return a tuple
containing the coerced values. When they can't be coerced, return None.
>>> coerce(2,'2')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: number coercion failed
Bad doc string or misimplementation? Or is it fixed in the latest release, (which I
haven't gotten around to installing yet)?
Regards,
Bengt Richter
More information about the Python-list
mailing list