下面是Python3.9中的一个协同例程
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start
@coroutine
def grep(pattern):
while True:
line = yield "I have to yield something here?"
if pattern in line:
# do something fancy to the line
yield line
else:
raise ValueError("err")由于line = yield正在接收和发送数据,因此我需要执行额外的next调用才能使其工作:
gg = grep("thing")
item = gg.send("That thing!")
print(item)
next(gg)
item = gg.send("That thing also!")
print(item)
next(gg)
item = gg.send("And what about here this thing.")
print(item)
next(gg)
item = gg.send("Not this.")
print(item)
next(gg)打印的内容:
That thing!
That thing also!
And what about here this thing.
Traceback (most recent call last):
File "/home/erasmose/Workspace/clustr/cmapper/temp.py", line 33, in <module>
item = gg.send("Not this.")
File "/home/erasmose/Workspace/clustr/cmapper/temp.py", line 16, in grep
raise ValueError("err")
ValueError: err如果我删除"next“调用:
gg = grep("thing")
item = gg.send("That thing!")
print(item)
item = gg.send("That thing also!")
print(item)
item = gg.send("And what about here this thing.")
print(item)
item = gg.send("Not this.")
print(item)输出为:
That thing!
I have to yield something here?
And what about here this thing.
I have to yield something here?有没有办法避免这些额外的“下一步”调用?
发布于 2021-06-16 23:12:55
您需要组合这两个yield语句,以便协程在同一个yield中发送和接收
不过,你仍然需要额外的收益才能开始这个过程。
如下所示:
@coroutine
def grep(pattern):
line = yield "I have to yield something here?" # receive the first one
while True:
if pattern in line:
line = yield line # send and receive in one yield statement
else:
raise ValueError("err")https://stackoverflow.com/questions/68005003
复制相似问题