[Python-Dev] sorted()

Delaney, Timothy tdelaney@avaya.com
Thu, 26 Sep 2002 11:13:27 +1000

> From: Greg Ewing [mailto:greg@cosc.canterbury.ac.nz]
> pinard@iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard):
> > The advantage is that the `.sorted()' method fits well within how
> > Python has evolved recently, offering more concise and legible
> > writings for frequent idioms.
> To support specialised non-in-place sorting algorithms,
> it could check whether its argument has a sorted()
> method, and if not, fall back on the general implementation.

Hmm - this actually suggests a couple more magic methods:


corresponding to "sort a copy" and "sort in-place".

Defining the rules for how these would be called requires a bit more thought
however. Do you want a sort() function to prefer __sort__ or __isort__?

def sort (seq, in_place=1):

    if in_place:
        return seq.__isort__()

        return seq.__sort__()

    seq = list(seq)
    return seq

So - if an in-place sort is specified, try to do one, throwing an exception
if it's not possible. Otherwise sort a copy.

This would allow a generic mechanism for objects to ort copies of
themselves, rather than blindly changing them to a list.

Would two methods be better for in-place and copy sort?

Tim Delaney