Python coroutines

Mar 10, 2013 22:43

I learned today that python generators can be run in reverse to create coroutines. The basic idiom is:

def myCoroutine():
while True:
x = (yield)
doSomethingTo( x )

Then you can use it by calling .send() to provide the return value of the yield expression. See a short course here: Read more... )

python, programming

Leave a comment

Comments 4

freelikebeer March 11 2013, 16:20:54 UTC
I started with his Generator Tricks for Systems Programmers which was the best explanation that I have read. Slide 75 [Processing Infinite Data] was where it got really interesting. I came away thinking that there had to be some kind of support in the runtime to manage the continually-yielding-iterable. I'm guessing that that is where the concurrency presentation is going to take me.

Reply

prock March 13 2013, 00:04:28 UTC
I've only make it to slide 33 yet, but it's a great read.

Reply

markgritter March 13 2013, 01:27:11 UTC
You don't really need any runtime support. You can think of it as a program transformation from

def myGenerator():
i = 0
while True:
yield i
i = i + 1

to something that under the hood looks like:

def startState():
return { 'i' : 0, 'first' : True }

def nextIteration( state ):
if not state['first']:
state['i'] = state['i'] + 1
else:
state['first'] = True
return state['i']

(Probably would have been better to show it as a class--- you could write your own class that looks like a generator to python because, hey, duck typing!)

Reply

prock March 13 2013, 04:33:51 UTC
random side note: being more of a mathematical than a languages type CS guy, it took me years to figure out that in "duck typing", duck was a noun and not a verb.

Reply


Leave a comment

Up