[Python-ideas] Function to return first(or last) true value from list
Terry Reedy
tjreedy at udel.edu
Thu Feb 20 17:05:43 CET 2014
On 2/20/2014 8:11 AM, אלעזר wrote:
>
>
>
> 2014-02-19 1:01 GMT+02:00 Steven D'Aprano
> <steve at pearwood.info
> <mailto:steve at pearwood.info>>:
> >
> > On Tue, Feb 18, 2014 at 04:25:28PM -0600, Ryan Gonzalez wrote:
> >
> > > In Python 2, you'd do this:
> > >
> > > next((x for x in mylist if x))
> >
> > That works fine in Python 3 too.
> >
>
> The problem with this approach, which I personally ran into a couple of
> days ago, is that raising StopIteration in the case of empty `mylist` is
> *not* what you want, in general. "first" assumes non-exhausted iterator;
> raising StopIteration is easily caught in the closest `for` loop, and
> you end up failing silently. But
>
> Errors should never pass silently.
>
> This is a case of an "almost working" solution, similar to the and-or
> "trenary" conditional operator. I think it's horrible. Non-advanced
> Python programmer may not be able to find such a bug.
>
> An implementation of first() should raise some other exception than
> StopIteration.
#untested
__missing = object()
def first(iterable, default=__missing):
for o in interable:
if o:
return o
else:
if default is not __missing:
return default
else:
raise ValueError("iterable has no true value and there is no
default")
--
Terry Jan Reedy
More information about the Python-ideas
mailing list