【发布时间】:2019-07-09 19:28:54
【问题描述】:
此问题与synchronous version 中的同一问题相关。 目标是设计将生成器或协程作为参数作为输入的装饰器。我的代码如下:
import asyncio
def say_hello(function):
async def decorated(*args, **kwargs):
return_value = function(*args, **kwargs)
if isinstance(return_value, types.AsyncGeneratorType):
print("Hello async generator!")
async for v in return_value:
yield v
else:
print("Hello coroutine!")
return await return_value
return decorated
@helpers.say_hello
async def generator():
for i in range(5):
await asyncio.sleep(0.2)
yield i
@helpers.say_hello
async def coroutine():
await asyncio.sleep(1)
return list(range(5))
async def test():
for v in generator():
print(v)
for v in coroutine():
print(v)
这给出的错误是:
'return' with value in async generator
我猜这只是静态检查decorated 包含yield 和return 的值。
有什么办法可以做到这一点吗? (除了在say_hello 中有一个参数来指定function 是生成器还是协程)。
【问题讨论】:
标签: python python-3.x asynchronous python-asyncio python-decorators