Redux: Allowing 'return obj' in generators

Dustin J. Mitchell dustin at
Sun Jun 10 21:57:05 CEST 2007

This question was first brought up in October of 2005[1], and was included in
the "Unresolved Issues" section of my microthreading PEP, which I have quietly
withdrawn from consideration due to lack of community interest.

PEP 255 says

    Q. Then why not allow an expression on "return" too?

    A. Perhaps we will someday.  In Icon, "return expr" means both "I'm
       done", and "but I have one final useful value to return too, and
       this is it".  At the start, and in the absence of compelling uses
       for "return expr", it's simply cleaner to use "yield" exclusively
       for delivering values.

As those of you who looked at my PEP or are familiar with some of the
implementations will realize, microthreaded functions are syntactically
generator functions, but semantically act as regular functions.  There
is a well-defined meaning to 'return x' in such a function: take the
value of x, and use it in the expression where this function was called.
For example:

def read_integer(sock):
    txt = yield sock.readline().strip()
        return int(txt)
        raise AppProtocolError("Expected an integer")

The implementation of the syntax would be similar to that of an
expressionless 'return', but supplying the expression_list to the
StopIteration's 'args' -- this is described quite well in Piet Delport's

Given this use-case (and note that I chose an example that will exercise
the interactions of try/except blocks with the StopIteration behavior),
is it time to revisit this issue?  BDFL said:

  I urge you to leave well enough alone. There's room for extensions
  after people have built real systems with the raw material provided by
  PEP 342 and 343.[3]

and Nick Coghlan said (to applause from GvR):

  I'm starting to think we want to let PEP 342 bake for at least one
  release cycle before deciding what (if any) additional behaviour
  should be added to generators.[4]

I think we have a decent number of implementations in the wild now
(I have learned of Christopher Stawarz's 'multitask'[5] since last
posting my PEP).  With 2.5.1 out, might I suggest this is worth
reconsidering for the 2.6 release?



More information about the Python-list mailing list