integer and string compare, is that correct?

Arnaud Delobelle arnodel at googlemail.com
Mon Jan 11 20:12:10 CET 2010


Nobody <nobody at nowhere.com> writes:

> On Sun, 10 Jan 2010 23:13:55 -0800, Dan Bishop wrote:
>
>>> If you actually need to perform comparisons across types, you can rely
>>> upon the fact that tuple comparisons are non-strict and use e.g.:
>>>
>>>         > a = 5
>>>         > b = '5'
>>>         > (type(a).__name__, a) < (type(b).__name__, b)
>>>         True
>>>         > (type(a).__name__, a) > (type(b).__name__, b)
>>>         False
>>>
>>> The second elements will only be compared if the first elements are equal
>>> (i.e. the values have the same type).
>> 
>> But this method gives you 3.0 < 2 because 'float' < 'int'.  Probably
>> not what you want.
>
> If you're comparing instances of entirely arbitrary types, what
> you probably want (and the only thing you're going to get) is an
> entirely arbitrary ordering.
>
> The main case where such a comparison makes sense is for algorithms which
> require a total ordering (e.g. tree-like structures), and those won't care
> if 3<2 so long as the axioms for a total ordering hold.

It won't work for several reasons.  Offhand I can think of two:

1. lists, tuples:

>>> [1] < ['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()

2. Partially ordered or unordered builtin types:

>>> 1j < 1+1j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: no ordering relation is defined for complex numbers

-- 
Arnaud



More information about the Python-list mailing list