VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • 对于Python中可被await对象的一点研究

 

Python3.5中新增加了关于async和await语法和定义了何为Coroutines对象,在平时使用时,会分不清哪些能够await,所以记录下对于可被await的对象的理解.

根据PEP 492,可被await的对象主要分为4类:

  • native coroutine object returned from a native coroutine function.
  • generator-based coroutine object returned from a function decorated with types.coroutine().
  • An object with an __await__ method returning an iterator.
  • Objects defined with CPython C API with a tp_as_async.am_await function, returning an iterator (similar to __await__ method).

对于以上的4种对象,我将就自己的理解进行下列解释,如有不同的意见欢迎指点.


1. Async定义的函数

在PEP 492中,同时也定义了async语法,主要用于在函数定义时,使该函数变为一个native coroutine function,也就是在用到async定义的函数时,一样能被await

1
2
3
4
5
async def func():
    pass
 
async def main():
    await func()

2. 装饰器types.coroutine()修饰的函数

但是不仅仅使用types.coroutine装饰器,函数必须使用yield from,并且后面返回一个Coroutine对象(即文中提到的除此之外的其他3种对象)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import types
import asyncio
from tornado.queues import Queue
 
= Queue()
 
 
@types.coroutine
def run():
    print("This is run")
    yield from q.put(1)
 
 
async def main():
    await run()
 
 
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

3. 有__await__方法的对象 

顾名思义,就是定义了__await__方法的对象也能被await,同时该方法必须返回iterator,否则就会报错
关于asyncio.future对象可被await,也是添加了__await__ = __iter__这一行
对于该类对象不是很好确定,通常可看源码来确定是否具有__await__方法

4. CPython中定义tp_as_async.am_await

还未尝试过编译CPython,所以对于这点并不是特别清楚,但是文档中也说了和__await__方法类似,同样要返回一个iterator


补充延伸:

最初想要搞清楚可被await的对象是因为在学习tornado过程中,要不断的使用async和await方法,为了在使用时能较清楚的明白使用条件,才去研究了await的使用条件.
而在tornado中,除了以上4点之外,我目前还了解能被await的对象或方法具有一个特征: 那就是他们都返回Awaitable或Future,比如说tornado.queues中的Queue,在使用过程中,会发现queue中有的方法可以被await,有的方法并不可以,在查看了源码之后,发现可被await的方法都是返回一个Future对象,而该对象是来自于asyncio的Future,其中实现了__await__,所以才能被await.


参考文献:<PEP 492>


__EOF__

 
本文作者神様大失败
本文链接:https://www.cnblogs.com/kami-dai-shpai/p/13845937.html


相关教程