[Python-ideas] Fwd: quantifications, and tuple patterns

Nick Coghlan ncoghlan at gmail.com
Sun Jan 15 03:36:22 CET 2012

On Sun, Jan 15, 2012 at 12:01 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> One disadvantage of returning a single value to represent both the success
> or failure of the quantification *and* the witness is that it leaves the
> caller vulnerable to this sort of bug:
> py> witness = any2([3, 0, 2, 4], lambda n: n%2==0)  # get first even number
> py> if witness:
> ...     print("first even number is,", witness)
> ... else:
> ...     print("everything is odd")
> ...
> everything is odd
> I don't have a good solution for this.

The way around it is to always return a tuple: empty if no answer was
found, a singleton-tuple if it was. That way truth-testing will always
give the right found/not-found answer, but in the found case you can
access the original object.

def any2(iterable, pred=bool):
   """Like any(pred(x) for x in iterable), but returns () if nothing
matches the predicate,
   otherwise (obj,), a singleton-tuple holding the first value that matched it.
   for obj in iterable:
       if pred(obj):
           return (obj,)
   return ()

py> found = any2([3, 0, 2, 4], lambda n: n%2==0)  # get first even number
py> if found:
...     print("first even number is,", found[0])
... else:
...     print("everything is odd")
first even number is 0


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list