
On Mon, Dec 9, 2019 at 9:43 PM Tim Peters <tim.peters@gmail.com> wrote:
[Guido]
The argument that first(it) and next(it) "look the same" doesn't convince me;
I'm sorry - I guess then I have absolutely no idea what you were trying to say, and read it completely wrong.
if these look the same then all function applications look the same, and that can certainly not have been Meertens' intention.
No argument on that from me ;-)
But if everyone thinks that first() should raise, fine, this thread is way too long already (I should have kept it muted :-).
It was being discussed. The 1-argument more-itertools `first()` does raise on an exhausted iterator, and that does make most sense to me. In my algorithms I usually "know" I'm not trying to take an element from an empty iterable, and have no use for a default value in such a case. Since there's no non-destructive way to assert that the iterable is not exhausted, raising an exception if it is exhausted is most useful.
_empty = object() a = first(iterable, _empty) if a is _empty: raise ...
is a PITA by comparison, as is my _current_ idiom:
for a in iterable: break else: raise ...
Plain old
a = first(iterable)
would be perfect - but only if it raised.
Thinking out loud here... What idiom are we trying to replace with one that's more obviously and whose semantics are easy to grasp? `first(iterable)` that raises is StopIteration is `next(iter(iterable))`. `first(iterable)` that defaults to None and doesn't raise is `next(iter(iterable), None)`. Now only if the raised exception changes do you end up with something like Tim's examples where more than one line is definitely needed. So I think the question is what problem are we trying to solve here? Is it the lack of knowledge of the 2-argument next() form? Or is it that people are regularly wanting the first item from an iterable and when it doesn't exist they want to raise an exception different from StopIteration (and what is that alternative exception)? If it's the former then I think the case could be made that more education of the one-liner might be all that's needed here. Now Guido did the research and showed that the stdlib doesn't seem to realize this form really exists, so it might be quite the education. ;) But if it's the latter then there's a greater savings in complexity from providing first() with those semantics. But once again the question becomes how often does that come up? I obviously have no answers to provide. :) My gut is suggesting that if it's the one-liner replacement it might not be worth it, but if it's to raise a different exception I could see more of a use for adding something to the stdlib.