On Wed, Oct 13, 2021 at 2:39 AM Christopher Barker firstname.lastname@example.org wrote:
On Tue, Oct 12, 2021 at 4:51 AM Chris Angelico email@example.com wrote:
Exactly: simple usage of next is often a bug. We need to be careful about this every time someone suggests that it's straight-forward to do next(iter(obj)).
<snip> > > Please give a real example of where calling first() and getting > ValueError is safer than calling next(iter(x)) and getting > StopIteration. So far, I am undeterred in believing that the two > exceptions have equivalent effect if the caller isn't expecting them.
I don't know about safer, but it is a clear example of why using next(iter(obj)) requires a pretty complete knowledge of the iteration protocol.
I can guarantee you I'd get some questions from my students when they got a StopIterationError!
If one DID write a first() function, it maybe or maybe not should raise a different exception, but it should certainly provide a better error message:
Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
Is not very helpful.
If they're actually writing it explicitly, like that, then this is a perfect opportunity to teach the meanings of iterators and next(). If it's buried behind a first() function, it would simply be an error, just like  is an error. Either way, there's no real difference between them, and asking "what is the first element of an empty collection?" is always going to result in an error.