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... )
Comments 4
Reply
Reply
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
Reply
Leave a comment