[Python-ideas] Map and filter should also convert StopIteration to RuntimeError

Ethan Furman ethan at stoneleaf.us
Sat Dec 13 00:19:38 CET 2014

On 12/12/2014 02:41 PM, Oscar Benjamin wrote:
> On 12 December 2014 at 22:33, Ethan Furman wrote:
>> And now it will raise an exception at the point where the error actually occurred.
> It won't because I wasn't using generators. The point I have been
> trying to make is that this isn't just about generators.

FWIW I agree that the real culprit is next() -- just about any other function that we call will raise an error exception
if something goes wrong, but in 'next's case, asking for the next item when there isn't one raises a flow-control
exception instead of an EmptyIterable exception.

Happily, we can write our own next() for our own modules (or even for built-ins if we're really adventurous!):


  unsafe_next = builtins.next

  _unset_ = object()

  def next(iterator, default=_unset_):
        return unsafe_next(iterator)
     except StopIteration:
        if default is _unset_:
           raise EmptyIterable
        return default


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141212/9cb4fbb0/attachment.sig>

More information about the Python-ideas mailing list