GeneratorExit masks StopIteration?
Chris Angelico
rosuav at gmail.com
Mon Jan 30 00:54:31 EST 2017
On Mon, Jan 30, 2017 at 4:24 PM, <inyeol.lee at gmail.com> wrote:
> 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.
When you close() a generator, it raises GeneratorExit into it, and
then silences any StopIteration or GeneratorExit that comes out of it.
If you need different behaviour, what you could do is explicitly
throw() into it:
>>> c.throw(GeneratorExit)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration: 1
which you'd obviously want to wrap in try/except, but at that point,
you have the result.
Maybe this could be a feature request - that generator.close() returns
the return value of the generator (or None if the GeneratorExit comes
out)?
ChrisA
More information about the Python-list
mailing list