Why does adding brackets around the yield call in the generator allow it to compile / run?

I have a method:

@gen.coroutine def my_func(x): return 2 * x 

mostly tornado coroutine.

I am making a list, for example:

 my_funcs = [] for x in range(0, 10): f = yield my_func(x) my_funcs.append(x) 

When trying to make this list comprehension, for example:

 my_funcs = [yield my_func(i) for i in range(0,10)] 

I realized that this is not valid syntax. It turns out that you can do this using () around the output:

 my_funcs = [(yield my_func(i)) for i in range(0,10)] 
  • Is this behavior (the syntax for wrapping a call to yield foo() in () such as (yield foo() ) to allow the execution of the above code) has a specific name type?
    • Is this some form of operator priority with yield ?
  • Is this behavior with yield documented somewhere?

Python 2.7.11 on OSX. This code really should work like in Python2 / 3, so understanding the above list is not a good idea (see here why the comp list above works in Python 2.7 but is broken down in Python 3).

+5
source share
1 answer

yield expressions must be enclosed in brackets in any context, except for the whole operator or the right part of the assignment:

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

This is indicated in the PEP, which presents yield expressions (as opposed to yield ), and this is implied by contexts in which yield_expr appears in the grammar , although no one expects you to read the grammar:

The yield expression must always be enclosed in parentheses, unless it occurs in a top-level expression on the right side of the assignment.

+5
source

Source: https://habr.com/ru/post/1258359/


All Articles