gpt4 book ai didi

python - 如何从python中的协程获取返回值

转载 作者:太空狗 更新时间:2023-10-29 20:31:32 25 4
gpt4 key购买 nike

我正在根据 http://www.dabeaz.com/coroutines/Coroutines.pdf 尝试协程管道

问题是,我怎样才能从 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())

通过这段代码我得到:

>>> pipe.send(10)
100

然后我想获取返回值而不是打印它,我尝试从 sink 中产生:

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

但它似乎不起作用,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

产生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)]

关于python - 如何从python中的协程获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18611142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com