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

Alex Martelli aleaxit at yahoo.com
Mon Oct 20 17:56:30 EDT 2003


On Monday 20 October 2003 11:43 pm, Raymond Hettinger wrote:
> Let's see what the use cases look like under the various proposals:
>> todo = [t for t in tasks.copysort() if due_today(t)]
> todo = [t for t in list.sorted(tasks) if due_today(t)]
> todo = [t for t in list(tasks, sorted=True) if due_today(t)]
>> genhistory(date, events.copysort(key=incidenttime))
> genhistory(date, list.sorted(events, key=incidenttime))
> genhistory(date, list(events, sorted=True, key=incidenttime))
>> for f in os.listdir().copysort(): . . .
> for f in list.sorted(os.listdir()): . . .
> for f in list(os.listdir(), sorted=True): . . .
>> To my eye, the first form reads much better in every case.
> It still needs a better name though.

You're forgetting the cases in which (e.g.) tasks is not necessarily a list, 
but any finite sequence (iterable or iterator). Then. e.g. the first job
becomes:
todo = [t for t in list(tasks).copysort() if due_today(t)]
todo = [t for t in list.sorted(tasks) if due_today(t)]
todo = [t for t in list(tasks, sorted=True) if due_today(t)]
and I think you'll agree that the first construct isn't that good then
(quite apart from the probably negligible overhead of an unneeded
copy -- still, we HAVE determined that said small overhead needs
to be paid sometimes, and needing to code list(x).copysort() when
x is not a list or you don't KNOW if x is a list adds one copy then).
> [Phillip J. Eby in a separate note]
>> > Wouldn't it need to grow key and cmpfunc, too?
>> Now, that "key" and "reverse" are available,
> there is no need for "cmp" in any new methods.

Sorry, but much as I dislike cmpfunc it's still opportune at times, e.g.
I'd rather code:
def Aup_Bdown(x, y):
 return cmp(x.A, y.A) or cmp(y.B, x.B)
for a in list.sorted(foo, cmp=Aup_Bdown): ...
than 
for a in list.sorted(
 list.sorted(foo, key=lambda x:x.B, reverse=True),
 key=lambda x: x.A): ...
or even
for a in list(foo).copysort(key=lambda x:x.B, reverse=True
 ).copysort(key=lambda x: x.A): ...
Alex


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /