On Fri, Mar 27, 2009 at 12:53 AM, Greg Ewing
Guido van Rossum wrote:
That +0 could turn into a +1 if there was a way to flag this as an error (at runtime), at least if the return is actually executed:
def g(): yield 42 return 43
for x in g(): print x # probably expected to print 42 and then 43
Perhaps the exception used in this case could be a different exception than StopIteration?
Would checking that the value is None be sufficient? Or do you want to distinguish between 'return' and 'return None'? That would feel rather strange to me.
Well currently there *is* a difference, because "return None" is a (phase 2) SyntaxError in a generator, while "return" isn't. But I don't really care if you cannot distinguish these two cases.
I'm inclined to regard this as an unnecessary complication. People are already trained to think of 'return' and 'yield' as quite different things. I don't know why they would suddenly start using 'return' when they mean 'yield'.
Because coroutines are mind-bendingly hard, and it's easy to confuse yield (pass a value back while keeping the stack frame) and return (pass a value back dropping the stack frame). The syntactic prohibition on "return <expr>" in generators currently helps people to be consistent. I'd like to keep this small crutch around so that people who are writing vanilla (== meant for iteration) generators are kept from accidentally introducing hard-to-debug problems. Perhaps the crux is that *if* you accidentally use "return <value>" in a vanilla generator expecting the value to show up somewhere, you are probably enough of a newbie that debugging this will be quite hard. I'd like not to have such a newbie trap lying around. -- --Guido van Rossum (home page: http://www.python.org/~guido/)