python coroutine协程

本文探讨了Python中如何将普通函数转化为协程函数,主要通过装饰器使其变为生成器,然后通过inspect.CO_ITERABLE_COROUTINE标志位将生成器转变为协程。协程在await表达式中可被调用,执行过程可通过迭代控制。协程对象是awaitable对象,当执行结束会抛出StopIteration异常。协程不应直接引发未处理的StopIteration异常。
摘要由CSDN通过智能技术生成
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值