any() and all() on empty list?
Ron Adam
rrr at ronadam.com
Wed Mar 29 19:47:06 EST 2006
Carl Banks wrote:
> Steve R. Hastings wrote:
>> I'm completely on board with the semantics for any(). But all() bothers
>> me. If all() receives an empty list, it will return True, and I don't
>> like that. To me, all() should be a more restrictive function than any(),
>> and it bothers me to see a case where any() returns False but all()
>> returns True.
>
> Perhaps a practical example will illustrate why all() returns False
> better than all this mathematical mumbo-jumbo.
>
> Ok, say you're writing a simple software management/bug tracking
> system. It manage another software package that is to have periodic
> releases, but the release can only be made when there are no
> outstanding bugs. You might have a line of code that looks like this:
>
> if all(bug.status == 'closed' for bug in bugs_filed):
> do_release()
>
> As you can see, the release will only happen if all the bugs are marked
> closed. But... what if no bugs have been filed? If all() were to
> return False on an empty sequence, the software couldn't be fixed until
> at least one bug had been filed and closed!
>
> The point is, whenever you have to test that every item in a list is
> true, it is almost always correct for the test to pass when the list is
> empty. The behavior of all() is correct.
>
>
> Carl Banks
Yes, But that should be a test for 'not any()'.
if not any(bug.status == 'open' for bug in bugs_filed):
do_release()
So to give a counter example...
Where we are assembling widgets in a manufacturing plant. Where we don't
want to go to the next step until *all* the sub parts are present.
if all(part.status == 'present' for part in unit):
do_release()
Oops! Some empty bins showed up at the next assembly station. ;-)
Cheers,
Ron
More information about the Python-list
mailing list