any(), all() and empty iterable

Mark Dickinson dickinsm at gmail.com
Tue Apr 14 16:47:05 EDT 2009


On Apr 14, 7:21 pm, Luis Alberto Zarrabeitia Gomez <ky... at uh.cu>
wrote:
> It's more than that. Python's following the rules here. Maybe it could be
> documented better, for those without a background in logic/discrete mathematics,
> but not changed.

Agreed.

I'd like to guess that in 93.7% of cases, when a programmer
has used all(seq) without having thought in advance about what the
right thing to do is when seq is empty, the current behaviour is
already the right one.  I tried to test this hypothesis, but a
Google code search for uses of all() turned up very little
besides definitions.  For example:

if all(t.already_filed() for t in my_tax_forms):
    go_to_bed_happy()
else:
    file_for_extension()

In the event that you didn't have any tax_forms, this
does the right thing.

The current definition also makes reasoning about programs and
program transformations easier, thanks to invariants like:

all(seq1 + seq2) === all(seq1) and all(seq2)

and

all(all(s) for s in seqs) === all(chain(*seqs))

and

any(not s for s in seq) == not all(seq)

These invariants wouldn't hold if all([]) were False, or raised
an exception.

IMO, the current behaviour meets both the practicality *and*
the purity criteria.

Mark



More information about the Python-list mailing list