Python 3.0 - is this true?

"Martin v. Löwis" martin at
Sun Nov 9 19:09:35 CET 2008

>> Yes, key= lets you sort anything anyway you want.
>>  >>> l=[1, '2', 3j]
>>  >>> sorted(l, key = str)
>> [1, '2', 3j]
> The problem here is that str() is degenerate, i.e. a != b does not imply 
> str(a) != str(b).

So why is this a problem? The sort algorithm is stable, so it gives a
deterministic result. Not a particularly useful one - but I don't see
that any order on these three values could be considered "useful".

>>  >>> sorted(l, key = id)
>> ['2', 3j, 1]
> And of course, this has to opposite problem, a == b does not imply id(a) == 
> id(b).  Whether either of these "problems" is really a problem obviously 
> depends on what you're trying to do.

And that's Terry's message entirely. Is is YOU who decides how you want
these things sorted (if you want to sort them). Python refuses the
temptation to guess.

> In 3.0, can you still order types?  In 2.x, you can do:
>>>> t1 = type(1)
>>>> t2 = type(1j)
>>>> t1 < t2
> False

By what criteria? When is a type smaller than another one?

> def total_order(o1, o2):
>    "Compare any two objects of arbitrary types"
>    try:
>       return o1 <= o2
>    except UncomparableTypesError:   # whatever the right name is
>       return type(o1) <= type(o2)
> and get the same effect as you had in 2.x.

You can still do that - but you also need to define the order that
types have in 2.x (namely, by name).

Completely emulating the sorting of 2.x is nearly impossible,
considering how complex that is.


More information about the Python-list mailing list