[Python-ideas] Proto-PEP on a 'yield from' statement

Carl Johnson carl at carlsensei.com
Sat Feb 14 02:57:30 CET 2009

Greg Ewing wrote:

> Antoine Pitrou wrote:
> > The problem I can see is that in normal iteration forms (e.g. a  
> "for" loop), the
> > argument to StopIteration is ignored. Therefore, a generator  
> executing such a
> > return statement and expecting the caller to use the return value  
> wouldn't be
> > usable in normal iteration contexts.
> How is this different from an ordinary function returning a
> value that is ignored by the caller?
> It's up to the caller to decide whether to use the return
> value. If it wants the return value, then it has to either
> use a 'yield from' or catch the StopIteration itself and
> extract the value.

I think there is a difference. I were to

 >>> def my_gen():
...     yield 1
...     return 2 #or "return finally 2" or whatever

I would would be very surprised at the result when putting it into a  

 >>> for i in my_gen():
...    print(i)

Where did the two go? Why did it disappear? Well, the answer is that  
the for-loop body ignored it, the same way the None emitted by a  
mutating function gets ignored. But that answer doesn't seem very  
compelling to me, just confusing.

-1 for returning from a generator.

-- Carl

More information about the Python-ideas mailing list