[Python-Dev] GeneratorExit is unintuitive and uneccessary

Igor Bukanov igor.bukanov at gmail.com
Thu Aug 24 01:44:21 CEST 2006


Regarding yield in the finally problem:

The current implementation throws RuntimeException after the yield
transfer the control back to the close method. If that is changed to
reporting a bad behavior and rethrowing GeneratorExit or its hidden
analog as suggested at the point of yield inside the generator, that
would nicely unwind possible outer finally blocks and close the
generator in any case.

With that close-as-return proposal it does not even require to change
the interpreter as the close method can simply loop like in
generator.triggerRetrunAfterTheYield
while generatorYielding:
  reportBadYield
  generator.triggerRetrunAfterTheYield

Of cause, a bad generator can still subvert even this in the same way
as return can be canceled, but with such changes one has to put
significant non-trivial efforts in writing such code.

Regards, Igor

On 8/24/06, Guido van Rossum  wrote:
> IIUC this is how return currently works -- in some sense it's an
> exception, but it can't be caught, and it won't escape from the
> current frame. Ditto for break/continue.
>
> The generator extensions are still very young, and I'm not against
> changing them somewhat in 2.6 or py3k. Perhaps GeneratorExit can be
> replaced by a treatment similar to the treatment of return. But I'm
> not sure it helps with the original problem; you could still put a
> yield in a finally clause that intercepts a return, just as today you
> can write
>
> def f():
>   for i in range(10):
>     print i
>     try:
>       return
>     finally:
>       break
>   print 999
>
> where the finally clause nullifies the return. In a generator, a yield
> in the finally clause still needs to be dealt with somehow.
>
>
> On 8/23/06, Igor Bukanov <igor.bukanov at gmail.com> wrote:
> > On 8/23/06, Phillip J. Eby wrote:
> > > Our original
> > > assumption was that if they could implement throw() then they could clearly
> > > implement close(), since close() was defined in terms of throw().  An
> > > asynchronous return might be another matter.
> >
> > Such asynchronous return can always be implemented via a special
> > hidden exception that is invisible to catch statements. I.e an
> > implementation of generators  can still use ___GeneratorExit
> > internally as long as it is not exposed to scripts.
> >
> > Regards, Igor
> >
>
>
> --
> --Guido van Rossum (home page: http://www.python.org/~guido/)
>


More information about the Python-Dev mailing list