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

Antoine Pitrou solipsis at pitrou.net
Sat Dec 13 23:36:33 CET 2014

On Sat, 13 Dec 2014 17:31:36 -0500
Terry Reedy <tjreedy at udel.edu> wrote:

> 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

I don't remember ever needing to write such code.



More information about the Python-ideas mailing list