GeneratorExit masks StopIteration?

inyeol.lee at inyeol.lee at
Mon Jan 30 00:24:07 EST 2017

Does generator.close() prevent raising StopIteration?

I'm trying to get the return value from coroutine after terminating it.
Here is simple test code:

$ python3
Python 3.6.0 (default, Dec 23 2016, 12:50:55) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def cor():
...   try:
...     item = yield
...   except GeneratorExit:
...     return 1
>>> c = cor()
>>> next(c)
>>> c.close()

I was expecting StopIteration from c.close() call, but Python 3.6 doesn't raise any.
Is this behavior expected? I couldn't find any reference regarding GeneratorExit and StopIteration interaction.

More information about the Python-list mailing list