copysort patch, was RE: [Python-Dev] inline sort option
Dan Aloni
da-x at gmx.net
Sat Oct 18 15:13:19 EDT 2003
On Sun, Oct 19, 2003 at 03:18:07AM +1000, Nick Coghlan wrote:
> Alex Martelli strung bits together to say:
> >> Guido> keys = D.keys()
> >> Guido> keys.sort()
> >> Guido> for key in keys:
> >> Guido> ...
> >>
> >>Current standard practice is also fine.
> >
> >Nolo contendere. It DOES feel a bit like boilerplate, that's all.
>
[...]
>
> Particularly since the following trick seems to work:
> ==============
> >>> def chain(method, *args, **kwds):
> method(*args, **kwds)
> return method.__self__
>
> >>> mylist = [1, 2, 3, 3, 2, 1]
> >>> print chain(mylist.sort)
> [1, 1, 2, 2, 3, 3]
> >>> mylist = [1, 2, 3, 3, 2, 1]
> >>> print chain(chain(mylist.sort).reverse)
>
[...]
>
> (Tested with Python 2.3rc2, which is what is currently installed on my home
> machine)
>
> Not exactly the easiest to read, but it does do the job of "sorted copy as
> an expression", as well as letting you chain arbitrary methods of any
> object.
(I'm new on this list)
Actually, there is way to do this out-of-the-box without the chain()
function:
>>> a = [1,2,3,3,2,1]
>>> (a, (a, a.sort())[0].reverse())[0]
[3, 3, 2, 2, 1, 1]
And there is also one for copysort():
>>> a
[1, 2, 3, 3, 2, 1]
>>> (lambda x:(x, x.sort())[0])(list(a))
[1, 1, 2, 2, 3, 3]
>>> a
[1, 2, 3, 3, 2, 1]
But that's probably not more readable.
Architect's Sketch...
--
Dan Aloni
da-x at gmx.net
More information about the Python-Dev
mailing list