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

Andy Buckley andy at insectnation.org
Sun Nov 21 20:39:25 CET 2010

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.

Most of the time, when I want to check that any or all of a collection
matches some test criterion, my iterable is not already in a valid form
to pass to any() or all(), and so I either have to explicitly re-code a
slightly modified version of the builtin, or wastefully use map() to
apply my test to *all* the items in the list. This is only a few lines
extra, but IMHO it would make these functions more useful and improve
the readability of this common idiom if the test function could be
supplied as an optional argument (which, if None, would default to the
standard boolean comparison):

For example, this unclear code:

    testval = False
    for i in mylist:
        if mytestfunction(i):
            testval = True
    if testval:

or this wasteful (and still unclear, IMO) version:

    mylist_bool = map(mytestfunction, mylist)
    if any(mylist_bool):

would be replaced by the very natural form:

    if any(mylist, test=mytestfunction):

The "test" keyword arg is perhaps not the best name, I admit, but no
other jumps prominently to mind ("match", "fn"?).

I think this would be a nice feature, and would improve the expressivity
of the language, much as the "key" optional arg to sort() does. Of
course, maybe I just don't know the nice way to do these sorts of
tests... please let me know if I missed something and am reinventing the
wheel ;)


More information about the Python-ideas mailing list