yield - statement or expression?

怎甘沉沦 提交于 2019-12-04 03:20:09

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.

shx2

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!