any(), all() and empty iterable

Arnaud Delobelle arnodel at googlemail.com
Tue Apr 14 09:27:59 EDT 2009


Tim Chase <python.list at tim.thechases.com> writes:

> Peter Pearson wrote:
>> On Sun, 12 Apr 2009 06:53:24 -0500, Tim Chase wrote:
>>>> >From the docs:
>>>>
>>>> all(iterable)
>>>>                 Return True if all elements of the iterable are
>>>> true. Equivalent
>>>>         to:
>>>>                 def all(iterable):
>>>>             for element in iterable:
>>>>                 if not element:
>>>>                     return False
>>>>             return True
>>> Then I'd say the comment is misleading.  An empty list has no item
>>> that is true (or false), yet it returns true.  The comment in the
>>> docs should read "Return False if any element of the iterable is
>>> not true" or "Return True if all elements of the iterable are true
>>> or if the iterable is empty."
>>
>> How 'bout: "Return True if no element of the iterable is not true"?
>
> 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...
>
> -tkc

In fact the doc is not just misleading, but plain wrong as the following
shows:

>>> def alwaystrue():
...     while True: yield True
... 
>>> all(alwaystrue())
[Python is stuck]

The iterable alwaystrue() satisfies the property "all elements of the
iterable are true", but all(alwaystrue()) does not return.  Instead one
could describe all()'s behaviour as:

    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.

-- 
Arnaud



More information about the Python-list mailing list