Comparison of different types does not throw exception
sholden at holdenweb.com
Thu Jul 12 19:47:46 CEST 2001
"Gordon Williams" <g_will at cyberus.ca> wrote in message
news:mailman.994953783.6278.python-list at python.org...
> I would like to know why python does not produce an exception when a
> comparison of objects of different types is made. For example:
> >>> 1 < "aaa"
> I cant see why anyone would like to have comparisons of different types as
> it has no meaning. It is a programming error and an exception should be
> This one tripped me up in an assert statement for a couple of hours. The
> assert statement was returning true when it should have been false to give
> me a warning that there was a problem. It was something like:
> lengthA= 3
> lengthB= "2"
> assert lengthA <= lengthB
> and was returning true
> It would have been *much* more helpful if it told be that I was comparing
> objects of different types.
This would somewhat undermine the value of Python's polymorphism, however,
which generally requires you to be able to use any old type of thing in any
context "as long as it makes sense" (in other words, as long as the objects
used have the correct methods). If you aren't using Python's object-oriented
features yet then this might seem a little unnecessary.
To ensure that two objects are of the same type you usually need to
if type(a) == type(b) and (other_conditions):
For comparisons, it was decided that allowing comparisons between object of
different types was necessary to allow (for example) sorting of arbitrary
More information about the Python-list