Comparisons of incompatible types

Tim Golden mail at timgolden.me.uk
Mon Dec 6 12:04:39 EST 2010


On 06/12/2010 16:59, TomF wrote:
> I'm aggravated by this behavior in python:
>
> x = "4"
> print x < 7 # prints False
>
> The issue, of course, is comparisons of incompatible types. In most
> languages this throws an error (in Perl the types are converted
> silently). In Python this comparison fails silently. The documentation
> says: "objects of different types *always* compare unequal, and are
> ordered consistently but arbitrarily."
>
> I can't imagine why this design decision was made. I've been bitten by
> this several times (reading data from a file and not converting the
> numbers before comparison). Can I get this to throw an error instead of
> failing silently?

Yes: switch to python 3 where this does throw an exception:

Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52
Type "help", "copyright", "credits" or "license
>>> 7 < "eight"
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
>>>

TJG



More information about the Python-list mailing list