Python "send" method doesn't change "next" value?

I am trying to execute the generator send function, I expected send to change the resulting value, so I tried in ipython:

In [17]: def z(n):
    ...:     i=0
    ...:     while(i<n):
    ...:         val=yield i
    ...:         print "value is:",val
    ...:         i+=1
    ...:
In [24]: z1=z(10)
In [25]: z1.next()
Out[25]: 0

In [26]: z1.send(5) # I was expecting that after "send", output value will become "5"
value is: 5
Out[26]: 1

In [27]: z1.next()
value is: None # I was expecting that z1.next() will restart from "6" because I sent "5"
Out[27]: 2

Well, I suppose I had a misunderstanding of what “send” really does, how to fix it?

+4
source share
1 answer

You get i, but you do not assign it the return value from the instruction yield. If you assign a return value, you will see the expected result:

def z(n):
    print 'Generator started'
    i=0
    while(i<n):
        val=yield i
        print "value is:",val
        if val is not None:
            i = val
        i+=1

z1=z(10)
print 'Before start'
print z1.next()
print z1.send(5)
print z1.next()

Conclusion:

Before start
Generator started
0
value is: 5
6
value is: None
7

: send next , yield, . value is: . send next , yield. send , yield, yield None.

+6

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


All Articles