'20' <= 100

Tim Peters tim.one at comcast.net
Thu May 1 19:32:42 EDT 2003


[Gerhard Häring]
>> I'd prefer Python to raise an exception if you compare a number to
>> something non-numeric.


[Jon Ribbens]
> For '<', '<=', '>' and '>=' I agree, but for '==' and '!=' I very much
> disagree since they have an obvious easy-to-define meaning (i.e.
> that objects of incompatible types are different).

That seems the best rule when it applies, and, e.g., 2.3's new datetime- and
set- module types try to live by that:

>>> from datetime import date
>>> t = date.today()
>>> t == 3
False
>>> t > 3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't compare datetime.date to int
>>>

>>> from sets import Set
>>> s = Set()
>>> s == 3
False
>>> s > 3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "C:\CODE\PYTHON\lib\sets.py", line 305, in __gt__
    self._binary_sanity_check(other)
  File "C:\CODE\PYTHON\lib\sets.py", line 314, in _binary_sanity_check
    raise TypeError, "Binary operation only permitted between sets"
TypeError: Binary operation only permitted between sets
>>>

A problem is that "incompatible types" isn't always the right distinction:

> As I understand it '<' etc can produce exceptions these days, does
> anyone know if '==' and '!=' can (in the absence of any weird non-
> standard user-defined classes overriding __cmp__ or somesuch)?

They can, and one particular case is common among people playing with
Unicode but still trying to mix it with 8-bit strings:

>>> u'xyz' == 'xyz'
True

>>> u'xyz' == chr(140)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8c in position 0:
ordinal ot in range(128)
>>>

The first example shows that str and unicode can be compared for equality
successfully.  The second shows that whether they can depends not on the
types, but on the specific values being compared.







More information about the Python-list mailing list