why any( ) instead of firsttrue( ) ?

Carl Banks pavlovevidence at gmail.com
Tue Jun 8 22:47:26 EDT 2010


On Jun 8, 4:08 pm, danieldelay <danielde... at gmail.com> wrote:
> Le 09/06/2010 00:24, Ian Kelly a crit :
>
> > Because it was designed as a replacement for "reduce(lambda x, y: x or
> > y, iterable)".  The problem arises when the iterable is empty.  What
> > false value should be returned?  If the iterable is a sequence of
> > bools, then None doesn't fit.  If the iterable is a sequence of
> > non-bool objects, then False doesn't fit.  In the case of reduce, the
> > problem is solved by explicitly specifying an initial value to be used
> > when the sequence is empty, but I guess GVR didn't feel that was
> > appropriate here.
>
> > Cheers,
> > Ian
>
> Thanks for your reply, it helps me to understand this choice wether I do
> not agree with it.
>
> "False" sounds natural for a function called "any()" which makes a
> boolean calculus
>
> "None" sounds natural for a function called "firsttrue()" which tries to
> retrieve an element.
>
> As the two make sense, I would have chosen the "firsttrue()" which is
> more powerfull...
>
> Perhaps "any()" whas choosen to keep a beautiful symmetry with "all()",
> that I can interprete only as a boolean calculus.
>
> Does GVR prefers beauty to power ?
>
> firsttrue(line.strip() for line in '\n\n \n CHEERS  \n'.split('\n'))


Given Python's approach to boolean semantics I'm surprised they did it
that way too.  Pretty much all other boolean logic in Python will
returns whatever value short circuits the operation.  Based on that, I
say it'd be perfectly consistent for any() and all() to do the same.

One nitpick: if no values are true it should return the final value,
not None, because "any([a,b,c])" should be exactly equivalent to "a or
b or c".

My best guess why they did it that is for the interactive prompt (so
that it would print True or False).  But then why didn't they do that
for "and" and "or"?

Having said that, the behavior of any() and all() is closer to the
boolean semantics I'd prefer.   The current semantics tempt too many
programmers to use erroneous hacks like:

x and y or z

or merely readability-lacking hacks like:

x or y



Carl Banks



More information about the Python-list mailing list