[Python-ideas] yield statements (was relaxing keyword usage restrictions)

ron3200 ron3200 at gmail.com
Fri Sep 9 23:34:45 CEST 2011

On Fri, 2011-09-09 at 21:23 +0200, Georg Brandl wrote:

> Now I checked properly: In fact, "yield" expressions after assignment
> operators are special-cased by the grammar, so that they don't need to
> be parenthesized [1]. In all other places, yield expressions must occur
> in parentheses.  For example:
>     myreturn = principal - yield
> Georg
> [1] I guess that's because it was thought to be a common case.  I agree
>     that it's not really helping readability.

Concerning yield without the parentheses.

       x = yield

I really think it should have been "x = (yield)" or  "x yield None".

Here is my reasoning.

What if yield was an assignment operator with similar usage rules as

      x = y               Assign x the object(s) y is assigned to.
      x yield y           assign x from yield, yield out y

In other words, the "yield" would never  appear to represent a value
directly.  That's one of the things that makes them confusing to read
and write.

Heres how the examples in pep 342 would change if yield worked more like

x = yield 42     ->    x yield 42

x = yield        ->    x yield None

x = 12 + (yield 42)

    y yield 42
    x = 12 + y

x = 12 + (yield)

    y yield None             # explicit is better than special casing None here.
    x = 12 + y

foo(yield 42)

    y yield 42


    y yield None

So it only adds one line to some things, but it makes for easier to read

Once we have yield statements like these, we can then add the ability to
do yield expressions by wrapping a yield statement inside parentheses.
And special casing (yield None) as (yield)

Oh, wait.. we already have that part. <wink>

It looks to me, that having yield statements, could help with explaining
yield expressions.  It may be worth doing just for that.


More information about the Python-ideas mailing list