General sort() function?

James T. Dennis jadestar at idiom.com
Tue Dec 17 20:36:22 EST 2002


 It seems like we frequently want to have a sort() function that
 returns a *copy* of an arbitrary sequence in a sorted order.

 I'm quite familiar with the discussion of why myList.sort() doesn't
 *return* such a copy.

 So here is my first stab at a general purpose sort() function that
 returns a sorted copy of an arbitrary sequence while trying to 
 preserve the type of the sequence:


def sort(s, postprocess=None):
    '''return a sorted copy of an arbitrary sequence
    '''
    if postprocess is None:
        try:
            ## ... to see if it's string like
            t = '' + s
            postprocess = ''.join
        except TypeError: pass
        try:
            t = () + s
            postprocess = tuple
        except TypeError: pass
        try:
            ## ... to let it sort itself.
            t = s[:]
            t.sort()
        except AttributeError:
        ## other seqence types will be converted to lists
            t = list(s[:])
            t.sort()
        if postprocess: return postprocess(t)
        else: return t

 ... I'm not sure if the "try: t.sort"  makes sense or should be moved.
 The idea is to support decorators or (sub)classes that provide  their own 
 sort (and slice/copy) operations.

 Are there any sequence types I'm missing?  Are their odd corner cases
 I'm failing to consider (particularly in the copying)?




More information about the Python-list mailing list