[Python-ideas] Function to return first(or last) true value from list
Steven D'Aprano
steve at pearwood.info
Thu Feb 20 23:00:40 CET 2014
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.
Failure to plan for the empty case, or test it, is not a problem unique
to next and iterators. I have read text books on Pascal written in the
70s and 80s that emphasise the need to test the linked list and tree
walking code with empty data structures.
--
Steven
More information about the Python-ideas
mailing list