[Python-ideas] Yield-From: Finalization guarantees

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Apr 1 23:30:45 CEST 2009

Nick Coghlan wrote:

> Any code that catches GeneratorExit without reraising it is highly
> suspect, just like code that suppresses SystemExit and KeyboardInterrupt.

As another perspective on this, I think Jacob's
example is another case of bogus refactoring.

If you think about it from the refactoring direction,
you start with something that catches GeneratorExit,
does some cleanup, and returns. That's fine.

But then you try to chop out just the part that
catches the GeneratorExit, without doing anything
to ensure that the main generator still returns

This is analogous to taking a block of code containing
a 'return' out of an ordinary function and putting it
in another function. If that's all you do, you can't
expect it to have the same result, because it only
returns from the inner function, not the outer one.

To correctly refactor Jacob's example, you need to
maintain an 'except GeneratorExit' in the main
generator somehow. Like 'return', it's not something
you can freely move across a refactoring boundary.


More information about the Python-ideas mailing list