R
Ron Adam
Carl said: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