为什么 print("text {}".format(yield i)) 是无效的语法,而 print("text {}".format((yield i))) 是有效的?

Why is print("text {}".format(yield i)) an invalid syntax whereas print("text {}".format((yield i))) is valid?

当我遇到这段代码时,我正在使用 this SO question on the generator send 函数

def coroutine():
    for i in range(1, 10):
        print("From generator {}".format((yield i)))
c = coroutine()
c.send(None)
try:
    while True:
        print("From user {}".format(c.send(1)))
except StopIteration: pass

如你所见,作者在 yield i 周围使用了 braces;我不明白为什么需要它。

str.format()doc 没有提到任何关于 format() 的参数是任何类型的。我确信我的困惑是因为我不知道 yield 语句的作用或调用时生成或生成的类型。

你能帮我理解为什么在 str.format 函数调用的 yield 周围需要大括号吗?

编译器不是很有帮助所以我不得不问这个问题

In [1]: def coroutine():
   ...:     for i in range(1, 10):
   ...:         print("From generator {}".format(yield i))
   ...: c = coroutine()
   ...: c.send(None)
   ...: try:
   ...:     while True:
   ...:         print("From user {}".format(c.send(1)))
   ...: except StopIteration: pass
  File "<ipython-input-1-024981190f27>", line 3
    print("From generator {}".format(yield i))
                                         ^
SyntaxError: invalid syntax

referenced generator article中,您可以阅读:

I recommend that you always put parentheses around a yield expression when you're doing something with the returned value, as in the above example. The parentheses aren't always necessary, but it's easier to always add them instead of having to remember when they're needed. (PEP 342 explains the exact rules, which are that a yield-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment.

因此,由于 yield i 的返回值用于 yield i 不是赋值 right-hand 侧的 top-level 表达式,因此它必须是括号内。

此外,此答案中还有更多信息: