[Python-Dev] inline sort option

Raymond Hettinger python at rcn.com
Thu Oct 16 13:49:57 EDT 2003

 [Tim Peters]
> > That said, since we're having a fire sale on optional sort arguments
> 2.4,
> > I wouldn't oppose an optional Boolean argument you could explicit
set to
> > have x.sort() return x.  For example,

[Michael Chermside]
> I just wanted to call everyone's attention to the fact that Tim may
> (again... <sigh>) have come up with a decent idea.
> Seriously... Guido (and apparently Tim and I too) insist that
> must return None since it mutates the list. Meanwhile, Kevin, Barry,
> perhaps others want to be able to write
> aList.sort().reverse().chainMoreHere().

Are you proposing something like:

    print mylist.sort(inplace=False)  # prints a new, sorted list while
                                      # leaving the original list intact

which would be implemented something like this:

    def inlinesort(alist, *args, **kwds):
        newref = alist[:]
        newref.sort(*args, **kwds)
        return newref

If that is what you're after, I think it is a good idea.  It avoids the
perils of mutating methods returning self.  It is explicit and pleasing
to write:

    for elem in mylist.sort(inplace=False):
        . . .

It is extra nice in a list comprehension:

    peckingorder = [d.name for d in duck.sort(key=seniority,

Instead of "inplace=False", an alternative is "inline=True".

Raymond Hettinger

More information about the Python-Dev mailing list