generator - How to get return value from coroutine in python -


i'm trying coroutines pipeline according http://www.dabeaz.com/coroutines/coroutines.pdf

the question is, how can value sink rather print it?

take code example

def coroutine(func):     def start(*args, **kwargs):         cr = func(*args, **kwargs)         next(cr)         return cr     return start   @coroutine def produce(target):     while true:         n = (yield)         target.send(n*10)   @coroutine def sink():     try:         while true:             n = (yield)             print(n)     except generatorexit:         pass   sk = sink() pipe = produce(sink()) 

with code get:

>>> pipe.send(10) 100 

then want return value rather print it, try yield sink:

@coroutine def sink():     try:         while true:             yield (yield)     except generatorexit:         pass 

but seems not working, pipe.send(10) still returns none rather generator.

so how shall return value?

why should pipe.send return generator? , going returned value?

whatever is, should done in sink.

you could, however, change functions to

@coroutine def produce(target):     while true:         n = (yield)         yield target.send(n*10)  @coroutine def sink():     try:         while true:             yield (yield)     except generatorexit:         pass 

to yield value yielded target, pipe.send(10) return 100 instead of printing it.

but mix producer , consumer, potentially give headache.


in response comment:

from collections import defaultdict  def coroutine(func):     def start(*args, **kwargs):         cr = func(*args, **kwargs)         next(cr)         return cr     return start  @coroutine def produce(key, target):     while true:         n = (yield)         target.send((key, n*10))  class sink(object):      def __init__(self):         self.d = defaultdict(lambda: none)         self.co = self.sink()      def send(self, *args):         self.co.send(*args)      @coroutine     def sink(self):         try:             while true:                 key, n = yield                 self.d[key] = max(self.d[key], n)         except generatorexit:             pass   sk = sink() pipea = produce("a", sk) pipeb = produce("b", sk)  pipea.send(10) pipea.send(20) pipea.send(40)  pipeb.send(20) pipeb.send(40) pipeb.send(60)  print sk.d.items() # [('a', 400), ('b', 600)] 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -