yield - Is there a difference between starting a Python 3 generator with next(gen) and gen.send(None)? -
when create python 3 generator , start run right away. error like:
typeerror: can't send non-none value just-started generator
and in order going (send messages or form it) first must call __next__
on it: next(gen)
or pass none gen.send(none)
.
def echo_back(): while true: r = yield print(r) # gen <generator object echo_back @ 0x103cc9240> gen = echo_back() # send not none , error below # expected though gen.send(1) # typeerror: can't send non-none value just-started generator # either of lines below "put generator in active state" # don't need use both next(gen) gen.send(none) gen.send('hello stack overflow') # prints: hello stack overflow)
both ways produce same result (fire generator).
what difference, if any, between starting generator next(gen)
opposed gen.send(none)
?
from generator.send()
:
when send() called start generator, must called none argument, because there no yield expression receive value.
calling next()
on generator starts execution until first yield
expression @ non-none
values can sent it, become value of yield
expression (e.g., x = yield
).
both next(gen)
, gen.send(none)
behave same way (i.e., no difference in usage).