[Python-Dev] return from a generator [was:PEP 380 (yield from a subgenerator) comments]

Carl Johnson cmjohnson.mailinglist at gmail.com
Fri Mar 27 07:59:02 CET 2009

>    def g():
>        yield 42
>        return 43

I don't see how the allowing return values in generators can fail to
be confusing for people new to Python. Of course, there are limits to
the degree that we should let people who are bad at Python dictate our
code practices, but I really just feel like this is going to confuse
people endlessly. "Where did my 43 go? Why didn't it come up in my

On the other hand, raising is a pretty well understood way of doing
control flow, if not value passing. But I can see why "raise
StopIteration(42)" might seem a bit obtuse. What if we just subclass
StopIteration and make something called "ReturnValue" or some-such.
Would a simple rename fix part of the problem:

    def g():
        yield 42
        raise ReturnValue(43)

> Do you really think the intent of the code would be any clearer
> if all the returns were replaced by raising StopIteration?

Doesn't "ReturnValue(43)" pretty clearly indicate what's going on? I
think part of the appeal of using "return" is that return is what's
used in ordinary functions, but if you think about it, you already
have to make your cooperative multitasking mini-thread different from
an ordinary function anyway by sprinkling yields throughout it. If
you're going that far, is it really so bad to also change the "return"
to a "raise ReturnValue"?

-- Carl Johnson

More information about the Python-Dev mailing list