Comparisons of incompatible types
Peter Otten
__peter__ at web.de
Mon Dec 6 12:04:00 EST 2010
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?
This change would break a lot of code, so it could not be made within the
2.x series. However:
Python 3.1.1+ (r311:74480, Nov 2 2009, 15:45:00)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "4" < 7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()
Peter
More information about the Python-list
mailing list