Generators (yield). Send() method. | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 9

Generators (yield). Send() method.

Can somebody please explain me how does send() method work in generators? https://code.sololearn.com/c28YFxTnaak2/?ref=app

16th Feb 2020, 12:06 PM
Mikhail
Mikhail - avatar
5 Respostas
+ 6
Send makes the next yield Docu says send(None) is equal to yield
16th Feb 2020, 3:30 PM
Oma Falk
Oma Falk - avatar
+ 6
I commented in code. that is indeed very interesting
16th Feb 2020, 6:36 PM
Oma Falk
Oma Falk - avatar
+ 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()
16th Feb 2020, 1:49 PM
Oma Falk
Oma Falk - avatar
+ 5
But if so, why in my second example (gen1) where generator uses double ā€œyieldā€ statement, b.send(100) prints out 100?
16th Feb 2020, 2:27 PM
Mikhail
Mikhail - avatar
+ 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ā€!
16th Feb 2020, 6:32 PM
Mikhail
Mikhail - avatar