Reputation: 41
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.
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
Upvotes: 3
Views: 472
Reputation: 1121266
You need to add another pair of parentheses around 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_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.
Inside a call expression (such as print(...)
), the parentheses can't be omitted.
Upvotes: 8