python中有内置的协程装饰器吗?我在tornado中见过类似的东西,但是在python中有类似这样的东西吗?
@coroutine
def func():
while True:
val = yield这样我就可以立即调用它并对其执行send操作,而无需首先使用next。我认为一个基本的方法是:
def coroutine(func):
@functools.wraps(func)
def wrapper_coroutine(*args, **kwargs):
f = func(*args, **kwargs)
next(f)
return f
return wrapper_coroutine但是我想知道python是不是有这个内置的东西。
发布于 2020-04-26 01:05:22
你可能已经为自己回答了这个问题,但为了让遇到这个问题的其他人受益,我也在寻找同样的东西,并找到了以下内容:
正如评论中所述,简单的答案是:在标准库中似乎没有这样的东西。
该站点上关于coroutines and their application主题的答案指向David Beazely的@coroutine decorator实现,为了方便起见,下面列出了其中的代码片段。
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和更高版本,使用示例的完整代码如下:
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中,这对我很有效
https://stackoverflow.com/questions/60573877
复制相似问题