copysort patch, was RE: [Python-Dev] inline sort option

Nick Coghlan ncoghlan at iinet.net.au
Sat Oct 18 13:18:07 EDT 2003


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.

Hi,

While I'm not an active Python contributor (yet), I've been lurking on 
python-dev since March.

Something was bugging me about the whole l.copysort() ('sortedcopy'?) idea. For 
whatever reason, the above comment crystalised it - if there's going to be a 
special 'sortedcopy' to allow minimalist chaining, then what about 
'reversedcopy' or 'sortedreversedcopy', or any of the other list methods that 
may be considered worth chaining?

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)
[3, 3, 2, 2, 1, 1]
 >>> print mylist
[3, 3, 2, 2, 1, 1]
 >>> mylist = [1, 2, 3, 3, 2, 1]
 >>> print mylist
[1, 2, 3, 3, 2, 1]
 >>> print chain(chain(list(mylist).sort).reverse)
[3, 3, 2, 2, 1, 1]
 >>> print mylist
[1, 2, 3, 3, 2, 1]
 >>> ==============

(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.

Regards,
Nick.

-- 
Nick Coghlan           |              Brisbane, Australia
ICQ#: 68854767         |               ncoghlan at email.com
Mobile: 0409 573 268   |   http://www.talkinboutstuff.net
"Let go your prejudices,
               lest they limit your thoughts and actions."




More information about the Python-Dev mailing list