为什么yield表达式不能成为函数参数?

时间:2021-09-18 23:29:44

I simply want to tidy up the following code.

我只是想整理下面的代码。

def well_known_generator():
    print('started')
    received = yield 100
    print(received)
    received = yield 200
    print(received)
    received = yield 300
    print('end')

g = well_known_generator()
print(next(g), g.send(None), g.send(None), g.send(None))

I just moved the yield expression into the print function, but a syntax error occurs. I'm just wondering why a yield expression can't be a function argument like below? If yield works like an expression, it should be okay as a function argument.

我刚刚将yield表达式移动到print函数中,但发生语法错误。我只是想知道为什么yield表达式不能像下面这样的函数参数?如果yield像表达式一样工作,它应该可以作为函数参数。

def well_known_generator():
    print('start')
    print(yield 100)
    print(yield 200)
    print(yield 300)
    print('end')

g = well_known_generator()
print(next(g), g.send(None), g.send(None), g.send(None))

SyntaxError: invalid syntax (<ipython-input-58-bdb3007bb80f>, line 3) 
  File "<ipython-input-58-bdb3007bb80f>", line 3
    print(yield 100)
              ^
SyntaxError: invalid syntax

1 个解决方案

#1


7  

You need to add another pair of parentheses around yield ...:

你需要在yield ...周围添加另一对括号:

def well_known_generator():
    print('start')
    print((yield 100))
    print((yield 200))
    print((yield 300))
    print('end')

The parentheses are part of the yield expression syntax:

括号是yield表达式语法的一部分:

yield_atom       ::=  "(" yield_expression ")"

but the parentheses are optional when it's the only expression in an assignment statement or a statement expression:

但当括号是赋值语句或语句表达式中唯一的表达式时,括号是可选的:

The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement.

当yield表达式是赋值语句右侧的唯一表达式时,可省略括号。

Inside a call expression (such as print(...)), the parentheses can't be omitted.

在调用表达式(例如print(...))中,不能省略括号。

#1


7  

You need to add another pair of parentheses around yield ...:

你需要在yield ...周围添加另一对括号:

def well_known_generator():
    print('start')
    print((yield 100))
    print((yield 200))
    print((yield 300))
    print('end')

The parentheses are part of the yield expression syntax:

括号是yield表达式语法的一部分:

yield_atom       ::=  "(" yield_expression ")"

but the parentheses are optional when it's the only expression in an assignment statement or a statement expression:

但当括号是赋值语句或语句表达式中唯一的表达式时,括号是可选的:

The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement.

当yield表达式是赋值语句右侧的唯一表达式时,可省略括号。

Inside a call expression (such as print(...)), the parentheses can't be omitted.

在调用表达式(例如print(...))中,不能省略括号。