comparing str's with ints

Bernhard Herzog bh at intevation.de
Tue Apr 30 08:07:09 EDT 2002


"Andrew Dalke" <dalke at dalkescientific.com> writes:

> Kragen:
> >Thus, heterogeneous collections are sortable.  This might be a wart;
> >once, couldn't raise exceptions,

cmp could raise exceptions. It's just that for builtin types it didn't.

In 1.5.2:
>>> class C:
...     def __cmp__(self, other):
...             raise TypeError
... 
>>> cmp(C(), C())
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in __cmp__
TypeError
>>> s = [C(), C()]
>>> s.sort()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in __cmp__
TypeError


> and now we're stuck with its old
> >behavior in this case for compatibility.  It's kind of nice that
> >heterogeneous collections are sortable, though.
> 
> Nice perhaps, but not true.
> 
> >>> a = [1, 1j]
> >>> a.sort()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: cannot compare complex numbers using <, <=, >, >=
> >>>

It used to be true, though. Python 1.5.2:

>>> a = [1, 1j]
>>> a.sort()
>>> a
[1j, 1]

Complex numbers used to be sorted by their real parts (resp. their
imaginary parts when the real parts were equal), IIRC.

Also IIRC: the requirement that comparisons between builtin types are
always possible was lifted because you can't reasonably compare a
unicode object with a string without knowing the string's encoding.

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/



More information about the Python-list mailing list