2013-09-04 6 views
8

にコルーチンからの戻り値を取得しますか?このコードではどうか、私は<code>sink</code>だけではなく、それを印刷から値を取得することができ、私は<a href="http://www.dabeaz.com/coroutines/Coroutines.pdf" rel="noreferrer">http://www.dabeaz.com/coroutines/Coroutines.pdf</a></p> <p>質問があるに応じてコルーチンパイプラインをしようとしているのpython

例えば、このコードを取る

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()) 

私が取得:

>>> pipe.send(10) 
100 

は、それから私は、私は、シンクから得しようとすると、戻り値を取得するのではなく、それを印刷したい:

@coroutine 
def sink(): 
    try: 
     while True: 
      yield (yield) 
    except GeneratorExit: 
     pass 

しかし、これはうまくいかないようですが、pipe.send(10)は、まだNone発電機。

戻り値はどのようにして得られますか?

答えて

1

なぜpipe.sendは発電機を返すのですか?そして、あなたは返された価値と何をするつもりですか?

何でもそれはsinkで行う必要があります。

あなたは、しかし、targetによって得られた値を得るために

@coroutine 
def produce(target): 
    while True: 
     n = (yield) 
     yield target.send(n*10) 

@coroutine 
def sink(): 
    try: 
     while True: 
      yield (yield) 
    except GeneratorExit: 
     pass 

にあなたの機能を変えることができるので、pipe.send(10)はちょうどそれを印刷するのではなく、100を返します。

これでプロデューサとコンシューマがミックスされました。これにより、頭痛を与える可能性があります。コメントに応答して


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)] 
+0

Iは、値A及び値Bに押した場合、フィルタ、放送、処理等の後、Aは、シンクする10の値を生成し、Bは8つの値を生成セイ沈む。私はAからの最大値とBからの最大値を求めますが、AからまたはBから生成された値はどのようにしてわかりますか?どのようにシンクでそれを行う上の任意のアイデア? – lxyu

+0

@lxyuキーを送信して、どのプロデューサが値を生成したかを知ることができます。シンクは、送信する値と最大値を知る状態を持つことができます。私の編集を参照してください。 – sloth

+0

必要なすべてのデータをカプセル化するオブジェクトを送信することをお勧めします。 – Cucu

関連する問題

 関連する問題