I can't understand the send
method. I understand that it is used to operate the generator. But
the syntax is here: generator.send(value)
.
I somehow can't catch why the value should become the result of the current yield
expression. I prepared an example:
def gen():
for i in range(10):
X = yield i
if X == 'stop':
break
print("Inside the function " + str(X))
m = gen()
print("1 Outside the function " + str(next(m)) + '\n')
print("2 Outside the function " + str(next(m)) + '\n')
print("3 Outside the function " + str(next(m)) + '\n')
print("4 Outside the function " + str(next(m)) + '\n')
print('\n')
print("Outside the function " + str(m.send(None)) + '\n') # Start generator
print("Outside the function " + str(m.send(77)) + '\n')
print("Outside the function " + str(m.send(88)) + '\n')
#print("Outside the function " + str(m.send('stop')) + '\n')
print("Outside the function " + str(m.send(99)) + '\n')
print("Outside the function " + str(m.send(None)) + '\n')
The result is:
1 Outside the function 0
Inside the function None
2 Outside the function 1
Inside the function None
3 Outside the function 2
Inside the function None
4 Outside the function 3
Inside the function None
Outside the function 4
Inside the function 77
Outside the function 5
Inside the function 88
Outside the function 6
Inside the function 99
Outside the function 7
Inside the function None
Outside the function 8
Well, frankly speaking, it is astonishing me.
- In the documentation we can read that when a
yield
statement is executed, the state of the generator is frozen and the value ofexpression_list
is returned tonext
‘s caller. Well, it doesn't seem to have happened. Why can we executeif
statement andprint
function insidegen()
. - How can I understand why
X
inside and outside the function differs? Ok. Let us assume thatsend(77)
transmits 77 intom
. Well,yield
expression becomes 77. Then what isX = yield i
? And how 77 inside the function converts into 5 when occurs outside? - Why the first result string doesn't reflect anything that is going on inside the generator?
Anyway, could you somehow comment on these send
and yield
statements?