[Python-ideas] Break the dominance of boolean values in boolean context

Guido van Rossum guido at python.org
Thu Sep 15 19:45:40 CEST 2011

On Thu, Sep 15, 2011 at 10:13 AM, Bill Janssen <janssen at parc.com> wrote:
> Alexander Belopolsky <alexander.belopolsky at gmail.com> wrote:
>> As someone suggested earlier in this thread, this can be achieved with
>> a very simple expression (not even a function!):
>> next(filter(None, S))
>> will return the first item x from S with bool(x) evaluating to True.
>> Further simplifying this is not worth slowing down all current uses of
>> any().
> Yeah, but you've got to think up that expression.  I agree that slowing
> down any() is not a good thing, but there's surely a place for this
> functionality -- probably more useful than any() itself.  I've wished
> several times that any() just returned the first hit.  Personally, I'd
> add a function some() that either returns a matching value or raises an
> exception.

I recall we discussed this, but I don't recall the exact reasons why
we (I?) decided that any() and all() should always return True/False.
I can guess that it was because of consistency with the return values
for any([]) and all([]), which have to be False and True,

Considering the use cases, and Python's pervasive use of
any-object-as-Boolean, I think it would have been fine if they had
been defined as follows:

def any(xs):
  x = False
  for x in xs:
    if x: break
  return x

def all(xs):
  x = True
  for x in xs:
    if not x: break
  return x

(Relying on two Pythonic properties of the for-loop: if the sequence
xs is empty, x is not set by the for-loop at all, and keeps its
previous value; if xs is not empty and the for-loop runs until xs is
exhausted, x keeps the last value assigned to it in the loop.)

I am not so sure that it is safe to change them now, however. Maybe
these upgraded versions can be added to some other module, e.g.
functools or itertools?

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list