any(), all() and empty iterable

John Posner jjposner at snet.net
Tue Apr 14 17:04:41 CEST 2009


Tim Chase wrote:
> I still prefer "Return False if any element of the iterable is not 
> true" or "Return False if any element in the iterable is false" 
> because that describes exactly what the algorithm does. Granted, 
> anybody with a mote of Python skills can tell that from the algorithm, 
> but if you're going to go to the trouble of documenting, you might as 
> well document what it does.  The code in the docs do not check the 
> truthiness of each element, it checks for the falseness (not-trueness) 
> of each element.  One might be able to defend it using logical 
> manipulations, but since Python strives for clarity...
Arnaud Delobelle wrote:
>     Return False as soon as the first false element in the iterable is
>     found.  Otherwise return True when the iterable is exhausted.
>
> Unfortunately it makes it much less obvious what the function is for and
> the Python implementation is a clearer explanation IMHO.
>
> So in the end, I think the doc reaches a good compromise: a short easy
> to understand english description that gives a clear idea of what all()
> is for, and a sample implementation for those who need/want the exact
> behaviour.
>   
IMO, you can't get around the essential ambiguity of the words "all", 
"any", "every", "no", etc. in the plain-English realm. The only way 
around this is to have the definition focus on the *individual* element 
of the iterable, not on the *collection* of elements. So I think Arnaud 
is headed in the right direction. My own choice would be to ignore his 
(very reasonable) objection to a definition that "makes it much less 
obvious what the function is for", and go with these:

  all(iterable) -- Return True if there does not exist an element in 
iterable that is False
  any(iterable) -- Return False if there does not exist an element in 
iterable that is True

These definitions *imply* the functions' short-circuiting behavior, but 
aren't as good as Arnaud's definition, which makes the short-circuiting 
explicit.

-John




More information about the Python-list mailing list