Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between starting a Python 3 generator with next(gen) and gen.send(None)?

When you create a Python 3 generator and start to run it right away. You get an error like:

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

And in order to going (send messages to it or get something form it) you first must 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 ways produce the same result (fire up the generator).

What is the difference, if any, between starting a generator with next(gen) as opposed to gen.send(None)?

like image 724
sargas Avatar asked Oct 19 '22 13:10

sargas


1 Answers

From generator.send():

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

Calling next() on the generator starts the execution until the first yield expression at which non-None values can be sent into it, which would become the value of that yield expression (e.g., x = yield).

Both next(gen) and gen.send(None) behave the same way (i.e., no difference in usage).

like image 160
Simeon Visser Avatar answered Nov 02 '22 05:11

Simeon Visser