Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does yield as assignment do? myVar = (yield)

Tags:

python

yield

I'm familiar with yield to return a value thanks mostly to this question

but what does yield do when it is on the right side of an assignment?

@coroutine
def protocol(target=None):
   while True:
       c = (yield)

def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr 
    return start

I came across this, on the code samples of this blog, while researching state machines and coroutines.

like image 289
Fire Crow Avatar asked Jan 07 '10 17:01

Fire Crow


2 Answers

The yield statement used in a function turns that function into a "generator" (a function that creates an iterator). The resulting iterator is normally resumed by calling next(). However it is possible to send values to the function by calling the method send() instead of next() to resume it:

cr.send(1)

In your example this would assign the value 1 to c each time.

cr.next() is effectively equivalent to cr.send(None)

like image 84
Tendayi Mawushe Avatar answered Oct 19 '22 13:10

Tendayi Mawushe


You can send values to the generator using the send function.

If you execute:

p = protocol()
p.next() # advance to the yield statement, otherwise I can't call send
p.send(5)

then yield will return 5, so inside the generator c will be 5.

Also, if you call p.next(), yield will return None.

You can find more information here.

like image 29
dusan Avatar answered Oct 19 '22 13:10

dusan