+ 9
Generators (yield). Send() method.
Can somebody please explain me how does send() method work in generators? https://code.sololearn.com/c28YFxTnaak2/?ref=app
5 Answers
+ 6
Send makes the next yield
Docu says send(None) is equal to yield
+ 6
I commented in code. that is indeed very interesting
+ 5
After reading the docs and thinking a while, I come to the following result:
a.send(100) does not send x but the yield expression
yield x.
Python must do so, otherwise it had problems handling send() for a generator gen(x,y):
while True:
yield(3x +4y)
What would you send in this case if send has exactly 1 argument.
As a model u can regard yield x as a variable that is created with first yield and can be manipulated with send()
+ 5
But if so, why in my second example (gen1) where generator uses double âyieldâ statement, b.send(100) prints out 100?
+ 5
So, send() does the same as next()?
P.S. If you run my code now, you will see a very interesting thing in the second example with double âyieldâ! It looks like these two âyieldsâ work one after another: with first ânext()â it prints out the first element of generator (so I guess the inner âyield xâ does this), but with second ânext()â it prints out âNoneâ (as if outer âyieldâ is doing this). And if I write âsend(value)â instead of the second ânext()â, it prints out the âvalueâ of âsendâ!