copysort patch, was RE: [Python-Dev] inline sort option
marktrussell at btopenworld.com
Tue Oct 21 06:31:28 EDT 2003
On Mon, 2003-10-20 at 23:49, Guido van Rossum wrote:
> Really? That would seem to just obfuscate things for the reader (who
> would have to scroll back potentially many pages to find the one-line
> definition of sort).
I think most readers would probably be able to guess what
for key in sort(d.keys()):
would do. If not then it's no worse than a user-defined function.
It's also a matter of proportion -- the important thing about the code
above is that it's walking over a dictionary. In most of my uses, the
sort() is just a detail to ensure reproducible behaviour.
In a new language I think you could make a case for the default
behaviour for dict iteration to be sorted, with a
walk-in-unspecified-order method for the cases where the speed really
does matter. Back in the real world, how about:
for key, value in d.sort():
(i.e. adding a sort() instance method to dict equivalent to:
def sort(d, cmp=None, key=None, reverse=False):
l = list(d.items())
l.sort(cmp, key, reverse)
). At least there's no question of an in-place sort for dicts!
> Why be so keen on saving 7 keystrokes?
It's not totally trivial - for me a list comprehension is noticeably
less readable when split over more than one line.
> How many calls to list.sorted do you expect to have in your average
Er, about 0.3 :-) In the project I'm working on, there are 52 sortcopy()
calls in 162 modules (about 18K LOC). Not enough to justify a built-in
sort(), but enough I think to make list.sorted() worthwhile.
More information about the Python-Dev