Reputation: 45281
See the console session below:
>>> def f(x):
... for _ in range(10):
... y = yield
... x.append(y)
... yield x
...
>>> x = []
>>> g = f(x)
>>> for _ in g:
... g.send(1)
...
[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Note that the .send()
method is causing the generator output to be printed to the screen. I believe it is the .send()
method causing because if the generator output is None
, then nothing is printed to the screen (which is the usual case with None
).
>>> x = []
>>> g = f(x)
>>> for i in g:
... g.send(1)
...
>>> x
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Additionally, if we just iterate through without sending any input, there is nothing printed to the screen (occurs with either version of f
above):
>>> x = []
>>> g = f(x)
>>> for i in g:
... pass
...
>>>
Can someone explain why does this output to the screen happens? I am thinking there is something interesting going on here but I don't know what it is.
To clarify, I surmise there is nothing complicated going on here than what happens when you do this:
>>> []
[]
The console is just repeating the result of an expression. But why is the console behaving as if there has been repeated expression entry in the case above?
Upvotes: 0
Views: 40
Reputation: 45281
I feel dumb. The answer is so simple! This is an expression:
g.send(1)
...and just like any other expression, it will be printed to the console- multiple times if inside of a loop:
>>> 0
0
>>> for _ in range(2):
... 0
...
0
0
Upvotes: 0
Reputation: 9968
From the Python docs:
The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value.
Each time you call the send()
method, it is returning the next value yielded by the generator.
In the interactive terminal, these returned results are printed to your screen. Nothing too magical.
Upvotes: 1