any(), all() and empty iterable
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue Apr 14 22:12:45 EDT 2009
On Tue, 14 Apr 2009 14:27:59 +0100, Arnaud Delobelle wrote:
> 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.
That's okay, the documentation doesn't say or imply that all() will
always return. Python doesn't make that promise about *any* function, and
it would be ridiculous to expect EVERY SINGLE Python function and class
to come with a warning that it won't return if you pass it an argument
that doesn't return.
def slow():
time.sleep(10**10)
return math.pi
math.cos(slow())
Is the documentation for cos() misleading because it doesn't warn that it
will take 300+ years to return? I don't think so.
Python guarantees that all() will return True if all the elements of the
iterable are true, but it doesn't make any promises about how much time
that will take. If there are six elements, and they're all true, you
can't know that they're all true until you have checked every one of
them. If there are six million elements, you have to check all six
million. If there are an infinite number of elements, how many do you
have to check, and how long will it take? This doesn't need to be spelled
out in the docs.
--
Steven
More information about the Python-list
mailing list