[Python-ideas] Yet another alternative name for yield-from

Nick Coghlan ncoghlan at gmail.com
Thu Apr 2 23:53:27 CEST 2009

Guido van Rossum wrote:
> On Thu, Apr 2, 2009 at 11:37 AM, Jacob Holm <jh at improva.dk> wrote:
>> Bruce Frederiksen wrote:
>>> Guido van Rossum wrote:
>>>> but how about 'return from'?
>>> or 'return finally'?(??) ...
>> Or what about "yield return"? That clearly marks the construct as belonging
>> in a generator. It also mixes well with the idea of a "yield raise" that I
>> mentioned in another mail (not a suggestion for this PEP).
> Not totally weird. After all Dave Beazley's trampoline uses "yield
> g()" to call a sub-generator and "yield x" to return a value x from a
> sub-generator to the calling generator via the trampoline's stack...

Using 'yield return' rather than a bare return wouldn't get any
objections from me. As has been said before, the current SyntaxError
definitely makes it easier to learn some of the ins and outs of generators.

That would leave us with:

'yield': pass a value back to and receive a value from this generator's
'yield from': pass control to a subgenerator and receive a value back
from it
'yield return': finish this generator with GeneratorReturn
'return': finish this generator with StopIteration

I think that leaves us with one remaining question: should we save the
return value on the generator iterator and make it available as the
return value of the close() method?

My inclination is that finalising a generator in a way that allows the
return value to be retrieved should be left out of the PEP for now, as
it is something that can be:
a) easily done externally to the generator*
b) added to close() later if we decide it would be a good idea

In order to leave that avenue open in the future however, close() must
be defined in the PEP to trap GeneratorReturn as well as StopIteration.

So +1 to having close() accept GeneratorReturn as a legitimate reaction
to being thrown GeneratorExit, but -0 on saving the return value on the
generator iterator object (at least in the initial version of the PEP)


* For example:

  def get_result_send(self, g, sentinel=None):
    # Using a sentinel to tell the generator to finish
      while 1:
      return None
    except GeneratorReturn as gr:
      return gr.value

  def get_result_throw(self, g, sentinel=GeneratorExit):
    # Using GeneratorExit to tell the generator to finish
      while 1:
        except sentinel:
      return None
    except GeneratorReturn as gr:
      return gr.value

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

More information about the Python-ideas mailing list