copysort patch, was RE: [Python-Dev] inline sort option
Alex Martelli
aleaxit at yahoo.com
Tue Oct 21 07:00:42 EDT 2003
On Tuesday 21 October 2003 12:31 pm, Mark Russell wrote:
> 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.
Incidentally,
for k in list.sorted(d):
will be marginally faster, e.g. (using the copysort I posted here, without The
Trick -- it should be just about identical to the list.sorted classmethod):
import copysort
x = dict.fromkeys(map(str,range(99999)))
def looponkeys(x, c=copysort.copysort):
for k in c(x.keys()): pass
def loopondict(x, c=copysort.copysort):
for k in c(x): pass
[alex at lancelot ext]$ timeit.py -c -s'import t' 't.loopondict(t.x)'
10 loops, best of 3: 2.84e+05 usec per loop
[alex at lancelot ext]$ timeit.py -c -s'import t' 't.looponkeys(t.x)'
10 loops, best of 3: 2.67e+05 usec per loop
i.e., about 10% better for this size of list and number of runs (quite a few,
eyeball x.keys()...:-). Nothing crucial, of course, but still.
Moreover, "list.sorted(d)" and "sort(d.keys())" are the same length, and
the former is conceptually simpler (one [explicit] method call, vs one method
call and one function call). Of course, if each keystroke count, you may
combine both "abbreviations" and just use "sort(d)".
> for key, value in d.sort():
>
> (i.e. adding a sort() instance method to dict equivalent to:
Why should multiple data types acquire separate .sort methods with
subtly different semantics (one works in-place and returns None, one
doesn't mutate the object and returns a list, ...) when there's no real
added value wrt ONE classmethod of list...? Particularly with cmp,
key, and reverse on each, seems cumbersome to me. Truly, is
list.sorted(d.iteritems()) [or d.items() if you'd rather save 4 chars
than a small slice of time:-)] SO "unobvious"? I just don't get it.
Alex
More information about the Python-Dev
mailing list