Python's simplicity philosophy

Alex Martelli aleaxit at yahoo.com
Sun Nov 16 10:15:45 EST 2003


Andrew Dalke wrote:
   ...
> The other three are in csv.py and look something like
>         quotechar = reduce(lambda a, b, quotes = quotes:
>                            (quotes[a] > quotes[b]) and a or b,
> quotes.keys())
> and are identical in intent to your use case -- select the
> object from a list which maximizes some f(obj).

I have already suggested, in a post on this thread's direct ancestor 9 days 
ago, the 100%-equivalent substitution in pure, simple, faster Python:

quotechar = None
for k in quotes:
    if not quotechar or quotes[k]>quotes[quotechar]:
        quotechar = k

or, for those who consider fast, simple, obviously correct code too boring,

quotechar = max([ (v,k) for k,v in quotes.iteritems() ])[-1]

which is more concise and at least as clever as the original.


> This suggests the usefulness of a new function or two,
> perhaps in itertools, which applies a function to a list

Nope -- itertools is not about CONSUMERS of iterators, which this one would 
be.  All itertools entries RETURN iterators.

> of values and returns the first object which has the
> maximum value, as in

Given that the sort method of lists now has an optional key= argument, I
think the obvious approach would be to add the same optional argument to min 
and max with exactly the same semantics.  I.e., just as today:

x = max(somelist)
somelist.sort()
assert x == somelist[-1]

we'd also have

x = max(somelist, key=whatever)
somelist.sort(key=whatever)
assert x == somelist[-1]

a perfectly natural extension, it seems to me.  I've found such total and 
extreme opposition to this perfectly natural extension in private 
correspondence about it with another Python committer that I've so far
delayed proposing it on python-dev -- for reasons that escape me it would
appear to be highly controversial rather than perfectly obvious.

> def longest(seq):
>     return imax(seq, len)

That would be max(seq, key=len) in my proposal.

> lines.  There were very few, and the paucity suggests
> that 'sum' isn't needed all that often.  Then again, I'm
> not one who suggested that that be a builtin function ;)

Right, that was my own responsibility.  I did identify about
10 spots in the standard library then (including substitutions
for reduce); that's more than the typical built-in has, even though
the tasks handled by the standard library are heavily slanted
to string and text processing, networking &c, and (of course)
"pure infrastructure", rather than typical application tasks.


Alex





More information about the Python-list mailing list