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

Raymond Hettinger python at rcn.com
Sun Oct 19 13:23:40 EDT 2003


[Alex Martelli]
> > But, for the general case: the BDFL has recently Pronounced that he
does
> > not LIKE chaining and doesn't want to encourage it in the least.
Yes,
> your
> > trick does allow chaining, but the repeated chain(...) calls are
> cumbersome
> > enough to not count as an encouragement IMHO;-).

[Nick Coghlan]
> Well, yes, that was sort of the point. For those who _really_ like
> chaining (I'm
> not one of them - I agree with Guido that it is less readable and
harder
> to
> maintain), the 'chain' function provides a way to do it with what's
> already in
> the language.


Remember, list.copysort() isn't about chaining or even "saving a line or
two".  It is about using an expression instead of a series of
statements.
That makes it possible to use it wherever expressions are allowed, 
including function call arguments and list comprehensions.

Here are some examples taken from the patch comments:

  genhistory(date, events.copysort(key=incidenttime))

  todo = [t for t in tasks.copysort() if due_today(t)]


To break these back into multiple statements is to cloud their intent
and take away their expressiveness.  Using multiple statements requires
introducing auxiliary, state-changing variables that remain visible
longer than necessary.  State changing variables are a classic source of
programming errors.  In contrast, the examples above are clean and show
their correctness without having to mentally decrypt them.

Scanning through the sort examples in the standard library, I see that
the multi-line, statement form is sometimes further clouded by having
a number of statements in-between.  In SimpleHTTPServer.py, for example

    list = os.listdir(path)
      . . . (yada, yada)
    list.sort(key=lambda a: a.lower())
      . . . (yada, yada, yada)
    for name in list:
         . . .

You see other examples using os.environ and such.

The forces working against introducing an in-line sort are:
* the time to copy the list (which Alex later showed to be irrelevant),
* having two list methods with a similar purpose, and 
* the proposed method names are less than sublime

If someone could come-up with a name more elegant than "copysort", I
the idea would be much more appetizing.


Raymond Hettinger





More information about the Python-Dev mailing list