[Python-Dev] PEP 380 (yield from a subgenerator) comments

P.J. Eby pje at telecommunity.com
Wed Mar 25 04:35:10 CET 2009


At 10:22 PM 3/24/2009 -0400, Steve Holden wrote:
>There is one non-trivial extension that I've been chewing over for a
>while. What if you want to yield not the values from the generator but
>some function of those values? The present proposal appears to have no
>way to specify that. What about extending the syntax somewhat to
>
>   yield expr for x from X
>
>The idea is that x should be a a bound variable in expr, but the "expr
>for x" could be optional to yield the existing proposal as a degenerate
>case.

That would be spelled:

    yield from (expr for x in X)

And the compiler could optionally optimize away the 
genexpr.  Assuming, of course, that this is considered valuable 
enough to implement in the first place, which I don't think it 
is...  especially not with the return bit factored in.

Now, if somebody came up with a different way to spell the extra 
value return, I wouldn't object as much to that part.  I can just see 
people inadvertently writing 'return x' as a shortcut for 'yield x; 
return', and then having what seem like mysterious off-by-one errors, 
or being confused by receiving a generator object instead of their 
desired non-generator return value.

It also seems weird that the only syntactically-supported way to get 
the generator's "return value" is to access it inside *another* 
generator...  which *also* can't return the return value to anyone!

But if it were spelled 'raise Return(value)' or 'raise 
StopIteration(value)' or something similar (or even had its own 
syntax!), I wouldn't object, as it would then be obvious how to get 
the value, and there could be no possible confusion with a regular 
return value.

The unusual spelling would also signal that something unusual (i.e., 
multitasking) is taking place, similar to the way some frameworks use 
things like 'yield Return(value)' to signal the end of a task and its 
return value, in place of a value in the stream.



More information about the Python-Dev mailing list