Comparisons of incompatible types
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Dec 8 04:47:21 EST 2010
On Wed, 08 Dec 2010 11:58:03 +1100, Ben Finney wrote:
> Carl Banks <pavlovevidence at gmail.com> writes:
>
>> On Dec 6, 4:17 pm, Steven D'Aprano <steve
>> +comp.lang.pyt... at pearwood.info> wrote:
>> > Nevertheless, I agree that in hindsight, the ability to sort such
>> > lists is not as important as the consistency of comparisons.
>>
>> I think that feeling the need to sort non-homogenous lists is
>> indictative of bad design.
>
> It can also be indicative of code written for a Python that doesn't have
> sets.
Or a list that contains unhashable objects.
Or a list that needs to be presented to a human reader in some arbitrary
but consistent order.
Or a doctest that needs to show the keys in a dict:
>>> d = myfunction()
>>> sorted(d.keys())
['ham', 'spam', 42, None]
(although that case is probably the weakest of the three).
> So there's no design error in wanting heterogenerous sequences to sort;
> it can be quite Pythonic (until the advent of the ‘set’ type).
Agreed, but in hindsight I think it would be better if there was a
separate lexicographic sort function, that guaranteed to sort anything
(including such unorderable values as complex numbers!), without relying
on the vagaries of the standard comparison operators.
Or at least anything printable, in which case sorted() with a key
function of lambda obj: (repr(type(obj)), repr(obj)) might work, I
suppose...
Then at least we could limit our arguments to how this hypothetical
lexicographic sort function was broken, instead of how all comparison
operators are broken :)
--
Steven
More information about the Python-list
mailing list