[Python-ideas] Yield-from: Nonexistent throw() and close()?

Bruce Frederiksen dangyogi at gmail.com
Sat Feb 21 16:11:43 CET 2009

Jacob Holm wrote:
> Hi Bruce
> Bruce Frederiksen wrote:
>> Jacob Holm wrote:
>>> I'd hate for this:
>>> def foo():
>>>    for i in xrange(5):
>>>        yield i
>>> to behave different from this:
>>> def foo():
>>>    yield from xrange(5)
>> These two forms already behave differently when generators are used 
>> (rather than xrange), why should they not also behave differently 
>> when non-generators are used?
> Not sure in what way you think they behave differently?  foo is a 
> generator in both cases, and as such has a send method.
True, but I was referring to the subgenerator/subiterable (xrange in 
your example); not to foo itself.  If xrange were a generator, #2 
behaves intentionally differently than #1.
> I am thinking of #2 as a simple rewrite/refactoring using the nifty 
> new feature.   Why should foo().send('bar') ignore the value in #1 and 
> raise an exception  in #2?
Thinking of #2 as a simple rewrite of #1 is not how this PEP defines 
yield from.

Unfortunately, AFAICT the *reason* for the difference is that the for 
statement was defined well before PEP 342 was adopted.  When PEP 342 was 
adopted, changing the for statement to honor the new generator methods 
would break legacy code.

But the "yield from" is being defined after PEP 342, so it may safely 
include these new capabilities.

Your example does not show why you would want to use send with foo.  As 
it is currently defined, there is no reason to do so.  If the yield in 
#1 is meant to be a yield *expression* who's values are acted on by foo 
somehow, then "yield from" won't work here, no matter how it's defined, 
because the yielded values are inaccessible to foo.  The same is true if 
xrange were a generator.

-bruce frederiksen

More information about the Python-ideas mailing list