使用协程作为装饰器 [英] Using a coroutine as decorator
本文介绍了使用协程作为装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这种情况下:
async def foo(f):
async def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
@foo
async def boo(*args, **kwargs):
pass
作为foo装饰器的装饰器对foo的调用是异步调用吗?
is the call to foo as a decorator for boo decorator an async call?
-首次 还有,一个人如何处理协程的调用链作为装饰器?
--First Also how does one handle calling chain of coroutines as decorators?
推荐答案
感谢@blacknght的评论,考虑
Thanks to @blacknght's comment, considering
def foo():
def wrapper(func):
@functools.wraps(func)
async def wrapped(*args):
# Some fancy foo stuff
return await func(*args)
return wrapped
return wrapper
和
def boo():
def wrapper(func):
@functools.wraps(func)
async def wrapped(*args):
# Some fancy boo stuff
return await func(*args)
return wrapped
return wrapper
作为两个装饰器,并且
@foo()
@boo()
async def work(*args):
pass
当foo
包装work
协程时,关键是要在两个装饰器中同时await
func(*arg)
.
As the foo
is wrapping the work
coroutine, the key is to await
the func(*arg)
in both decorators.
这篇关于使用协程作为装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文