[Python-ideas] Possible PEP 380 tweak

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Oct 30 05:09:04 CEST 2010

Guido van Rossum wrote:

> This seems to be the crux of your objection. But if I look carefully
> at the expansion in the current version of PEP 380, I don't think this
> problem actually happens: If the outer generator catches
> GeneratorExit, it closes the inner generator (by calling its close
> method, if it exists) and then re-raises the GeneratorExit:

Yes, but if you want close() to cause the generator to finish
normally, you *don't* want that to happen. You would have to
surround the yield-from call with a try block to catch the
GeneratorExit, and even then you would lose the return value
from the inner generator, which you're probably going to

> Could it be that you are thinking of your accelerated implementation,

No, not really. The same issues arise either way.

> It looks to me as if using g.close() to capture the return value of a
> generator is not of much value when using yield-from, but it can be of
> value for the simpler pattern that started this thread.

My concern is that this feature would encourage designing
generators with APIs that make it difficult to refactor the
implementation using yield-from later on. Simple things
don't always stay simple.

> def summer():
>   total = 0
>   try:
>     while True:
>       total += yield
>   except GeneratorExit:
>     raise StopIteration(total)  ## return total

I don't see how this gains you much. The generator is about
as complicated either way.

The only thing that's simpler is the final step of getting
the result, which in my version can be taken care of with
a fairly generic helper function that could be provided
by the stdlib.


More information about the Python-ideas mailing list