GeneratorExit masks StopIteration?

inyeol.lee at gmail.com inyeol.lee at gmail.com
Mon Jan 30 02:17:09 EST 2017


On Sunday, January 29, 2017 at 10:47:09 PM UTC-8, Chris Angelico wrote:
> On Mon, Jan 30, 2017 at 5:38 PM,  <inyeol.lee at gmail.com> 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

I found PEP-342 describes this behavior - silencing other GenExit or StopIteration.

BTW, the reason why I was checking this was to find a solution on how to get return value from coroutine without relying on some sentinel value, something like (not tested):

def accumulator():
  sum = 0
  try:
    while True:
      sum += yield
  except GeneratorExit:
    return sum

Any alternatives? Explicitly throwing GenExit looks like a hack.



More information about the Python-list mailing list