integer and string compare, is that correct?

Peter Otten __peter__ at web.de
Sun Jan 10 12:37:27 EST 2010


Somebody 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).

The same type *name*. To play it safe you'll have to compare the id, too:

>>> items = []
>>> for i in range(2):
...     class A: pass
...     items.append(A())
...
>>> sorted(items, key=lambda a: (type(a).__name__, a))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: A() < A()
>>> sorted(items, key=lambda a: (type(a).__name__, id(type(a)), a))
[<__main__.A object at 0x14dfbd0>, <__main__.A object at 0x14dfc50>]

Peter



More information about the Python-list mailing list