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
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/RS53UN46OS5BDGO67GC4BONXV5J2RU5I/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to