[Python-ideas] Possible PEP 380 tweak

Nick Coghlan ncoghlan at gmail.com
Sat Oct 30 06:26:48 CEST 2010

On Sat, Oct 30, 2010 at 2:05 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> To give some formal semantics to the new statement:

Oops, those would be some-formal-but-incorrect semantics that made the
StopIteration exceptions visible in the current frame. Fixed below to
actually kill the current frame properly, letting the generator
instance take care of turning the return value into a StopIteration

   # RETURN FROM semantics
   _i = iter(EXPR)
   _m, _a = next, (_i,)
   # _m is a function or a bound method;
   #  _a is a tuple of arguments to call _m with;
   # both are set to other values further down
   while 1:
       # Move the generator along
       # Unlike YIELD FROM, we convert StopIteration
       # into an immediate return (since this is a tail call)
           _y = _m(*_a)
       except StopIteration as _e:
           return _e.value

       # Yield _y and process what came back in
           _s = yield _y
       except GeneratorExit as _e:
           # Request to exit
               # Don't reuse _m, since we're bailing out of the loop
               _close = _i.close
           except AttributeError:
               # Unlike YIELD FROM, we return the
               # value of the inner close() call
               return _close()
           # If there is no inner close() attribute,
           # we just return None
       except BaseException as _e:
           # An exception was thrown in; pass it along
           _a = sys.exc_info()
               _m = _i.throw
           except AttributeError:
               # Can't throw it in; throw it back out
               raise _e
           # A value was sent in; pass it along
           if _s is None:
               _m, _a = next, (_i,)
               _m, _a = _i.send, (_s,)
   # Unlike YIELD FROM, this is a statement, so there is no RESULT

Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list