Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top