[Python-ideas] Provide a 'key' argument for all() and any() builtins

Paul Moore p.f.moore at gmail.com
Mon Jul 23 17:18:11 CEST 2012


On 23 July 2012 15:55, Guido van Rossum <guido at python.org> wrote:
> On Sun, Jul 22, 2012 at 9:36 PM, Raymond Hettinger
> <raymond.hettinger at gmail.com> wrote:
>>
>> On Jul 22, 2012, at 11:03 PM, Giampaolo Rodolà wrote:
>>
>> This would be similar to 'key' argument already available for min(), max()
>> and sorted() and would let user decide what must be considered True and what
>> not.
>>
>> There's no need.   We already have:
>>
>>     >>> all(predicate(x) for x in iterable)
>>     >>> any(predicate(x) for x in iterable)
>
> In addition, there's a reason why the key= parameter to sort, sorted,
> max and min can't be replaced with a similar idiom: all these return
> the *original* object(s) and the key= parameter affects only the
> comparison; for example, try max(1,-2,3,-4, key=abs).
>
> Whereas for the current proposal, the value returned by the key would
> also determine the outcome -- and then there is no advantage over
> using the comprehension. More general, if you can first apply the
> transformation (the key function) and then the aggregation function
> (min/max/etc.), there's no need to combine the transformation and the
> aggregation. But in all the cases that have a key= parameter, this is
> not so.

To put it yet another way, the key= parameter encapsulates the
decorate-process-undecorate pattern, and that pattern doesn't apply to
any/all.

Paul.



More information about the Python-ideas mailing list