首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用Python协程时,如何避免额外的迭代?

在使用Python协程时,如何避免额外的迭代?
EN

Stack Overflow用户
提问于 2021-06-16 22:46:03
回答 1查看 26关注 0票数 0

下面是Python3.9中的一个协同例程

代码语言:javascript
复制
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调用才能使其工作:

代码语言:javascript
复制
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)

打印的内容:

代码语言:javascript
复制
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“调用:

代码语言:javascript
复制
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)

输出为:

代码语言:javascript
复制
That thing!
I have to yield something here?
And what about here this thing.
I have to yield something here?

有没有办法避免这些额外的“下一步”调用?

EN

回答 1

Stack Overflow用户

发布于 2021-06-16 23:12:55

您需要组合这两个yield语句,以便协程在同一个yield中发送和接收

不过,你仍然需要额外的收益才能开始这个过程。

如下所示:

代码语言:javascript
复制
@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")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68005003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档