Is there a difference between running a Python 3 generator with the following (gen) and gen.send (None)?

When you create a Python 3 generator and start running it right away. You will receive an error:

TypeError: can't send non-None value to a just-started generator

      

And in order to go (send messages or receive something from it) you first have to call __next__

on it: next(gen)

or pass None to it gen.send(None)

.

def echo_back():
    while True:        
        r = yield
        print(r)

# gen is a <generator object echo_back at 0x103cc9240>
gen = echo_back()

# send anything that is not None and you get error below
# this is expected though
gen.send(1)

# TypeError: can't send non-None value to a just-started generator

# Either of the lines below will "put the generator in an active state"
# Don't need to use both
next(gen)
gen.send(None)

gen.send('Hello Stack Overflow')

# Prints: Hello Stack Overflow)

      

Both methods give the same result (start the generator).

What is the difference, if any, between starting the generator with next(gen)

as opposed to gen.send(None)

?

+3


source to share


1 answer


From generator.send()

:

When send () is called to start a generator, it must be called with None as an argument, because there is no yield expression that could receive a value.



A call next()

on the generator starts execution until the first expression yield

to which no values ​​can be sent None

, which will become the value of that expression yield

(for example, x = yield

>).

Both next(gen)

both gen.send(None)

behave the same (i.e. no difference in usage).

0


source







All Articles