[Python-ideas] Add stop=exception option to next() (was Re: PEP 479 and take())

Terry Reedy tjreedy at udel.edu
Sat Dec 13 23:31:36 CET 2014


On 12/13/2014 7:45 AM, Oscar Benjamin wrote:
> On 10 December 2014 at 18:35, Guido van Rossum <guido at python.org> wrote:

> If you had both next() and take() to choose from then the only time
> next() would be preferable is when you want to leak StopIteration (a
> pattern that is now largely broken by PEP 479).
>
>> BTW did you know that next(iterator, default) returns default if the
>> iterator is exhausted? IOW this will never raise StopIteration. It's similar
>> to dict.get(key, default) or getattr(obj, attrname, default).
>
> I more often find that I want an error than a default value and of

I once proposed, either here or on python-list, and propose again,
that the signature of next be expanded so that the user could specify 
the ending exception.  If possible, the stop object could either be an 
exception class, which would be called with a generic message, or an 
exception instance.

Then the awkward

try:
   item = next(it)
except StopIteration:
   raise ValueError('iterable must not be empty') from None

would simply be, for instance,

item = next(it, stop=ValueError('iterable must not be empty'))

The doc for next could say that, except in __next__ methods, the default 
stop exception, StopIteration, should be either overriden or caught, to 
prevent it from leaking out of the containing function.

No need for a new builtin to change the exception.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list