Comparison of different types does not throw exception

Nick Perkins nperkins7 at home.com
Fri Jul 13 20:15:32 EDT 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"
> 1
>
> 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
> produced.
>
> 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.
>
> Regards,
>
> Gordon Williams
>
>


I agreed with you completely,...until I thought of a good use for the
'consistent but arbitrary' result of such comparisons.

Suppose you want to use a list to represent a heterogenous set.  You don't
care about the order of things, but you want to know if two such sets are
the same.  You can sort a list of heterogenous types, and although the
resulting order may be 'arbitrary', at least it will be 'consistent'.  That
is, two lists that have the same elements in a different order can be
sorted, and then compared element-wise:


def equal(a,b): return a==b
def both(a,b): return (a and b)
def samelist (L1, L2):
    return reduce( both, map(equal,L1,L2), 1 )

def show_compare(a,b):
    print 'a=', a, 'b=', b
    if samelist(a,b): print 'ARE the same'
    else: print 'are NOT the same'

a = [ 1, 'one', 2, 'two' ]
b = [ 1, 2, 'one', 'two' ]

show_compare(a,b)

a.sort(); b.sort()
show_compare(a,b)


OUTPUT:

a= [1, 'one', 2, 'two'] b= [1, 2, 'one', 'two']
are NOT the same

a= [1, 2, 'one', 'two'] b= [1, 2, 'one', 'two']
ARE the same


Without the ability to compare, and therefore sort, a heterogenous list, it
would be much harder, (or at least slower?) to do this.







More information about the Python-list mailing list