statement or expression?

So, I've been reading this, and found out about sending values to generator.

And now I'm kinda confused. Is yield a statement or an expression? It doesn't use parenthesis syntax, like functions, so it looks like statement. But it returns value, so it's like expression.

Not so long ago I've had this conversation about "Why python doesn't have 'if x=foo(): (...)'?" (why can't we assign in if statement condition). I said, that statements are atomic, so assignment statement and if statement should be separated. Now, I don't know what to think anymore.

== EDIT ==

I did my fair share of reading.

http://docs.python.org/2/reference/expressions.html#generator.send - "The value argument becomes the result of the current yield expression."

So, yield HAS value. I get it, that all docs say it's a statement, but if statement may have value, then what the hell is the difference between expression and statement?

Also, I know what are generators, coroutines, etc, etc. I need meta-semantics, or semantics for docs :D

== FINAL ANSWER ==

Apparently, yield can be both. Just read those answers: (1) and (2) - I found them most helpful.


yield is an expression. It used to be a statement, and it's most commonly used as an entire statement, but in Python 2.5, it was turned into an expression as part of new coroutine support. It's still commonly referred to as the "yield statement", partly due to outdated documentation and knowledge and partly because it's mostly used as a statement anyway. You can read about that in PEP 342.

Aside from the following forms:

yield whatever
x = yield whatever

a yield expression must be parenthesized wherever it occurs, to avoid ambiguity in the syntax.


According to the grammar:

yield_stmt: yield_expr

and

yield_expr: 'yield' [testlist]

That is, yield x can be both, depending on the context:

 if foobar:
    yield x   # statement

 y = yield x   # expression

This expression/statement duality might be confusing, but is totally in the spirit of python, compare for loops vs for comprehensions, if statement vs. conditional operator, lambda vs def .


yield is statement.

However, it is a good point you're making, about this syntax: x = (yield y) . Off the top of my head, I can't think of other statements in python which can be used like that.

It's useful to read the docs, and of course, this legendary question.

链接地址: http://www.djcxy.com/p/9216.html

上一篇: Java,计算两个日期之间的天数

下一篇: 陈述或表达?