Oddity with 'yield' as expression - parentheses demanded

Chris Angelico rosuav at gmail.com
Thu Aug 1 02:25:55 EDT 2013


Was playing around with yield inside a lambda and ran into a distinct oddity.

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600
32 bit (Intel)] on win32
>>> foo=lambda x: yield(x)
SyntaxError: invalid syntax
>>> def foo(x):
	return yield(x)
SyntaxError: invalid syntax
>>> def foo(x):
	x=yield(x)
	return x
>>> foo=lambda x: (yield x)

If yield is an expression, why does it need extra parentheses around
it? [1] suggest that "(yield x)" is an expression that can elide the
parens only when it "is the sole expression on the right hand side of
an assignment statement", and presumably there's a similar rule
allowing the non-expression form "yield x" to omit the parens. Why is
this so? Why is it not simply an expression on its own?

[1] http://docs.python.org/3.3/reference/expressions.html#grammar-token-yield_expression

ChrisA



More information about the Python-list mailing list