首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >邮箱: Python @coroutine装饰器

邮箱: Python @coroutine装饰器
EN

Stack Overflow用户
提问于 2020-03-07 10:28:16
回答 1查看 145关注 0票数 0

python中有内置的协程装饰器吗?我在tornado中见过类似的东西,但是在python中有类似这样的东西吗?

代码语言:javascript
复制
@coroutine
def func():
    while True:
        val = yield

这样我就可以立即调用它并对其执行send操作,而无需首先使用next。我认为一个基本的方法是:

代码语言:javascript
复制
def coroutine(func):
    @functools.wraps(func)
    def wrapper_coroutine(*args, **kwargs):
        f = func(*args, **kwargs)
        next(f)
        return f
    return wrapper_coroutine

但是我想知道python是不是有这个内置的东西。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-26 01:05:22

你可能已经为自己回答了这个问题,但为了让遇到这个问题的其他人受益,我也在寻找同样的东西,并找到了以下内容:

正如评论中所述,简单的答案是:在标准库中似乎没有这样的东西。

该站点上关于coroutines and their application主题的答案指向David Beazely的@coroutine decorator实现,为了方便起见,下面列出了其中的代码片段。

代码语言:javascript
复制
def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr
    return start

回复@DocDriven的评论;上面是David Beazely实现的直接副本,它将适用于v3.2之前的Python版本。对此question的公认答案给出了更全面的解释和讨论,但在PythonV3.2中,.next()已被内置的自由函数next()所取代。因此,当使用Python3.2版或更高版本时,对cr.next()的调用被替换为对自由函数next(cr)的调用。

更新David Beazely的原始实现以使用Python版本3.2和更高版本,使用示例的完整代码如下:

代码语言:javascript
复制
def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        next(cr)
        return cr
    return start

# Example use
if __name__ == '__main__':
    @coroutine
    def grep(pattern):
        print("Looking for %s" % pattern)
        while True:
            line = (yield)
            if pattern in line:
                print(line)

    g = grep("python")
    # Notice how you don't need a next() call here
    g.send("Yeah, but no, but yeah, but no")
    g.send("A series of tubes for pythons")
    g.send("python generators rock!")

在Python v3.7.3中,这对我很有效

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60573877

复制
相关文章

相似问题

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