lxy*_*xyu 9 python generator coroutine
我正在根据http://www.dabeaz.com/coroutines/Coroutines.pdf尝试coroutines管道
问题是,我怎样才能从中获取价值sink而不仅仅是打印它?
以此代码为例
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())
Run Code Online (Sandbox Code Playgroud)
使用此代码,我得到:
>>> pipe.send(10)
100
Run Code Online (Sandbox Code Playgroud)
然后我想得到返回值而不是打印它,我试图从接收器中产生:
@coroutine
def sink():
try:
while True:
yield (yield)
except GeneratorExit:
pass
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用,pipe.send(10)仍然返回None而不是发电机.
那么如何获得返回值呢?
为什么要pipe.send归还发电机?您将如何处理返回值?
不管是什么,都应该在 内完成sink。
但是,您可以将您的功能更改为
@coroutine
def produce(target):
while True:
n = (yield)
yield target.send(n*10)
@coroutine
def sink():
try:
while True:
yield (yield)
except GeneratorExit:
pass
Run Code Online (Sandbox Code Playgroud)
产生由 产生的值target,因此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)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4630 次 |
| 最近记录: |