GeneratorExit masks StopIteration?

Chris Angelico rosuav at
Mon Jan 30 01:46:55 EST 2017

On Mon, Jan 30, 2017 at 5:38 PM,  <inyeol.lee at> wrote:
> On Sunday, January 29, 2017 at 9:54:44 PM UTC-8, Chris Angelico wrote:
>> ...
>> When you close() a generator, it raises GeneratorExit into it, and
>> then silences any StopIteration or GeneratorExit that comes out of it.
> Chris,
> Thanks for the info. Is this (GenExit silencing StopIteration) documented somewhere?
> I was suspecting this but couldn't find any reference.

Actually..... think this might be incorrect. I didn't look in the
docs, I looked in the source code, so my information is guaranteed
accurate; this is where I would expect the information to be:

As a general rule, a generator shouldn't be leaking StopIteration. In
a future version of Python, this will trigger RuntimeError. (You can
get that behaviour in 3.6 with a future import, too.) So what this
really means is that close() will suppress any GeneratorExit, or the
generator returning, both of which are normal occurrences. The only
significant thing is that the generator's return value could usefully
be propagated out of close().


More information about the Python-list mailing list