【发布时间】:2021-09-01 09:52:03
【问题描述】:
这是 Python 3.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
如果我删除“下一个”调用:
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?
有什么方法可以避免那些额外的“下一个”调用?
【问题讨论】:
标签: python python-3.x generator coroutine yield