yield - statement or expression?
Asked Answered
F

2

9

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.

Floris answered 22/11, 2013 at 10:22 Comment(4)
yield is a statementCrissie
You can also read this article jeffknupp.com/blog/2013/04/07/…Meleager
Just wondering, why is statement vs expression important? I myself never really think about it. =/Bachelorism
I like to know structure of language I use, also - I like to play with parsers, formal languages, etc. From where I sit, it's like itching brain.Floris
A
16

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.

Atc answered 22/11, 2013 at 10:39 Comment(1)
Hah! So, after all, I was right, when claiming that each python statement is atomic. That clears my head, thanks a lot ;)Floris
P
0

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.

Platitude answered 22/11, 2013 at 10:23 Comment(1)
It also returns a value if used with the .send() facility of a generator.Beautifully

© 2022 - 2024 — McMap. All rights reserved.