Change StopIteration handling inside generator-like builtins
PEP 479 (https://www.python.org/dev/peps/pep-0479/) changed the rules around generators: if it would have leaked StopIteration, it instead raises RuntimeError. This converts hard-to-debug premature termination into easily-spotted exceptions, but it applies only to actual generator functions. Implementing a map-like function as a generator means you're safe: def poof(x): if x == 5: raise StopIteration # Leak! return x * 3 def mymap(func, it): for value in it: yield func(value) for n in mymap(poof, range(10)): print(n) Boom! RuntimeError that highlights the source of the StopIteration. Similarly, using a list comprehension is safe: [poof(n) for n in range(10)] # raises StopIteration But using the built-in map() will silently terminate: for n in map(poof, range(10)): print(n) I propose to grant PEP 479 semantics - namely, that a StopIteration during the calling of the mapped function be translated into a RuntimeError. Likewise for filter(), guarding the predicate function, and all similar functions in itertools: accumulate, filterfalse, takewhile/dropwhile, starmap, and any that I didn't notice. ChrisA
participants (3)
-
Chris Angelico
-
Oscar Benjamin
-
Soni L.