In [8]: async def funcc():
...: print('2333')
...: return '2333'
In [14]: x = funcc()
In [15]: try:
...: x.send(None)
...: except StopIteration as exc:
...: print(exc.value)
2333
2333
In [2]: @asyncio.coroutines.coroutine
...: def f():
...: print('2333')
...: return '2333'
In [3]: x = f()
In [4]: try:
...: x.send(None)
...: except StopIteration as exc:
...: print(exc.value)
2333
2333
上面代码很相似,从上面就可以看出 是如何把一个普通函数变为协程函数的。通过send传递参数,若不需要参数传递 None 就好。上面代码中 f
是一个普通函数,通过装饰器 asyncio.coroutines.coroutine
, 装饰后变为一个协程函数(同时也是生成器);
下面看一下 asyncio.coroutines.coroutine
源代码:
def coroutine(func):
"""Decorator to mark coroutines.
If the coroutine is not yielded from before it is destroyed,
an error message is logged.
"""
if inspect.iscoroutinefunction(func): # 如果是协程函数就直接返回
# In Python 3.5 that's all we need to do for coroutines
# defined with "async def".
return func
if inspect.isg