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

Chris Angelico rosuav at gmail.com
Fri Dec 12 22:21:10 CET 2014


On Sat, Dec 13, 2014 at 8:14 AM, Terry Reedy <tjreedy at udel.edu> wrote:
> I propose that map.__next__ convert StopIteration raised by func to
> RuntimeError, just as generator.__next__ now does for StopIteration raised
> by executing a generator function frame.  (And same for filter().)
>
> class newmap:
>     "Simplified version allowing just one input iterable."
>     def __iter__(self):
>         return self
>     def __init__(self, func, iterable):
>         self.func = func
>
>         self.argit = iter(iterable)
>     def __next__(self):
>         func = self.func
>         args = next(self.argit)  # pass on expected StopIteration
>         if func is None:
>             return args
>         else:
>             try:  # new wrapper
>                 return func(args)
>             except StopIteration:
>                 raise RuntimeError('func raised StopIteration')

(I'm not sure why you have the "if func is None" check. Currently
map() doesn't accept None as its function. But that could equally be
implemented below if you wish.)

I propose a much MUCH simpler version of map, then:

def newmap(func, iterable):
    """Simplified version allowing just one input iterable."""
    for val in iterable:
        yield func(val)

Et voila! Conversion of StopIteration into RuntimeError.

ChrisA


More information about the Python-ideas mailing list