Issue 22761: Catching StopIteraion inside generator expression. (original) (raw)

Inside a list comprehension expression, if a StopIteration exception is raised, the interpreter assumes the exception was raised by the object Iterated buy the list comprehension expression.

For example, this generator will never stop, and will keep returning empty tuples:

def izip(*args): iters = [iter(obj) for obj in args] while True: yield tuple(next(it) for it in iters) x = izip([1,2],[3,4]) print(next(x)) #(1,3) print(next(x)) #(2,4) print(next(x)) #()

(One copy of a message is enough; I unlinked the duplicate.)

I am not sure what you mean by you initial sentence, but I do not think it is correct. In any case, "next(it) for it in iters" is a generator expression, not a list comprehension. The tuple call swallows the StopIteration, so the behavior is correct.

If you want to discuss further, please ask on python-list, also accessible at news.gmane.com either as a web page or as newsgroup gmane.comp.python.general.