Why does adding parenthesis around a yield call in a generator allow it to compile/run?
<p>I have a method:</p>

<pre><code>@gen.coroutine
def my_func(x):
    return 2 * x
</code></pre>

<p>basically, a tornado coroutine.</p>

<p>I am making a list such as:</p>

<pre><code>my_funcs = []
for x in range(0, 10):
    f = yield my_func(x)
    my_funcs.append(x)
</code></pre>

<p>In trying to make this a list comprehension such as:</p>

<pre><code>my_funcs = [yield my_func(i) for i in range(0,10)]
</code></pre>

<p>I realized this was invalid syntax. It <a href="http://chat.stackoverflow.com/transcript/message/33540588#33540588">turns out you can do this</a> using <code>()</code> around the yield:</p>

<pre><code>my_funcs = [(yield my_func(i)) for i in range(0,10)]
</code></pre>

<ul>
<li>Does this behavior (the syntax for wrapping a <code>yield foo()</code> call in () such as <code>(yield foo() )</code> in order to allow this above code to execute) have a specific type of name?

<ul>
<li>Is it some form of operator precedence with <code>yield</code>?</li>
</ul></li>
<li>Is this behavior with <code>yield</code> documented somewhere?</li>
</ul>

<p>Python 2.7.11 on OSX. This code does need to work in both Python2/3 which is why the above list comprehension is not a good idea (see <a href="http://stackoverflow.com/a/32139977/1048539">here</a> for why, the above list comp works in Python 2.7 but is broken in Python 3).</p>

<p><code>yield</code> expressions must be parenthesized in any context except as an entire statement or as the right-hand side of an assignment:</p>

<pre><code># If your code doesn't look like this, you need parentheses:
yield x
y = yield x
</code></pre>

<p>This is stated in the <a href="https://www.python.org/dev/peps/pep-0342/" rel="nofollow">PEP that introduced <code>yield</code> expressions</a> (as opposed to <code>yield</code> statements), and it's implied by the contexts in which <code>yield_expr</code> appears in the <a href="https://docs.python.org/2/reference/grammar.html" rel="nofollow">grammar</a>, although no one is expecting you to read the grammar:</p>

<blockquote>
  <p>A yield-expression must always be parenthesized except when it
      occurs at the top-level expression on the right-hand side of an
      assignment.</p>
</blockquote>

python python-2.7 tornado coroutine