[Python-ideas] Adding an optional function argument to all() and any() builtins

Andy Buckley andy at insectnation.org
Mon Nov 22 02:34:57 CET 2010

On 21/11/10 23:12, Steven D'Aprano wrote:
> Andy Buckley wrote:
>> I may be missing a standard idiom, but it seems to me that the any(...)
>> and all(...) builtins are unnecessarily limited by requiring that the
>> iterable they take as an argument is already in a form suitable for the
>> intended kind of boolean comparison.
> Yes, just like every function requires its input to already be in a form
> suitable for whatever the function expects to do. Just as any() and
> all() expect their argument to be truth-values (not necessarily True or
> False, but values to be inspected for their truthness), so sum() expects
> input consisting of numbers. Would you expect to be able to write this?
> mylist = ["a12", "b13", "c14", "d15"]
> sum(mylist, convert=lambda s: int(s[1:]))
> I hope not. Converting its input into a suitable format is not the
> responsibility of sum. sum's responsibility begins and ends with adding
> the input, any conversions should be done either externally:
> mylist = ["a12", "b13", "c14", "d15"]
> newlist = [int(s[1:]) for s in mylist]
> sum(newlist)
> or lazily using a generator expression as the argument to sum:
> mylist = ["a12", "b13", "c14", "d15"]
> sum(int(s[1:]) for s in mylist)
> There are variations on this using built-in map, itertools.imap, and
> similar.

Ok, I like this argument: thanks for making it ;)  If there weren't
generator expressions, I would still argue for a keyword in this case,
as any/all have usefulness on objects more general than one would pass
to sum... but there are gen exps, so I'm more than happy.

To reiterate, though, for those who like me have a blank day and fail to
realise that generator expressions are a neat and powerful idiom in this
case, I think it would be nice to mention this in their documentation.

Thanks all,

More information about the Python-ideas mailing list