[Python-ideas] Parametrized any() and all() ?

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Jan 16 12:20:54 CET 2013


On 16 January 2013 10:30, Tarek Ziadé <tarek at ziade.org> wrote:
> Hello
>
> any() and all() are very useful small functions, and I am wondering if it
> could be interesting to have them work
> with different operators, by using a callable.
>
> e.g. something like:
>
> import operator
>
> def any(iterable, filter=operator.truth):
>     for element in iterable:
>         if filter(element):
>             return True
>     return False
>
>
> For instance I could then us any() to find out if there's a None in the
> sequence:
>
> if any(iterable, op=lambda x: x is None):
>     raise SomeError("There's a none in that list")
>
>
> Granted, it's easy to do it myself in a small util function - but since
> any() and all() are in Python...

I wouldn't write a util function for this. The resulting code
    any(iterable, op=func)
is not really shorter, easier or clearer than the current methods
    any(map(func, iterable))
    any(func(x) for x in iterable)


Oscar



More information about the Python-ideas mailing list