[Python-ideas] Function to return first(or last) true value from list

אלעזר elazarg at gmail.com
Thu Feb 20 23:38:01 CET 2014


2014-02-21 0:00 GMT+02:00 Steven D'Aprano <steve at pearwood.info>:
>
> On Thu, Feb 20, 2014 at 04:14:17PM +0000, Oscar Benjamin wrote:
> > On 20 February 2014 16:05, Terry Reedy <tjreedy at udel.edu> wrote:
> > >>
> > >> An implementation of first() should raise some other exception than
> > >> StopIteration.
> [...]
>
> > It's easy enough to do if you know that bare next is a bad thing.
>
> Say what? Why do you say that next(it) is a bad thing?
>
> > More-itertools does it the way I would but has a long comment
> > wondering whether it should actually raise StopIteration:
> >
https://github.com/erikrose/more-itertools/blob/master/more_itertools/more.py#L37
> >
> > The thing is just that bare next is not something that's widely
> > recognised as being dangerous. I've seen examples of this kind of bug
> > in samples from many Python aficionados (including at least one from
> > you Terry).
>
> Why is it dangerous, and what kind of bug?
>
> If you're talking about the fact that next(it) can raise StopIteration,
> I think you are exaggerating the danger. Firstly, quite often you don't
> mind if it raises StopIteration, since that's what you would have done
> anyway. Secondly, I don't see why raising StopIteration is so much more
> dangerous than (say) IndexError or KeyError.
>
I had this bug just the other day. I did not plan for the empty case, since
it was obvious that the empty case is a bug, so I relied on the exception
being raised in this case. But I did not get the exception since it was
caught in a completely unrelated for loop. It took me a while to figure out
what's going on, and it would've taken even more for someone else, not
familiar with my assumption or with the whole StopIteration thing (which I
believe is the common case). An IndexError or a KeyError would have been
great in such a case.

It is *very* similar to the "and or" story.

---
Elazar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140221/bf769118/attachment-0001.html>


More information about the Python-ideas mailing list