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

Ron Adam rrr at ronadam.com
Mon Nov 22 01:29:25 CET 2010



On 11/21/2010 01:39 PM, 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.
>
> 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
>              break
>      if testval:
>          foo()

This has the advantage that it doesn't need to iterate the whole list. 
Sometimes you can't beat a nice old fashion loop. ;-)

I would write it like this...

     def test_any(iterable, test=bool):
         for i in iterable:
             if test(i):
                 return True
         return False


Then it would read fine in your program.

     if test_any(my_list, my_test_function):
         foo()


Cheers,
   Ron




More information about the Python-ideas mailing list