PEP 530 -- 异步推导式

摘要

PEP 492和PEP 525使用async/await语法引入了协程。PEP 530建议添加list,set,dict推导式和生成器推导式的异步版本。

理论和目标

对如下代码做了改进。

result = []
async for i in aiter():
if i % 2:
result.append(i)

可以写成异步推导式的方式简化上面代码:

result = [i async for i in aiter() if i % 2]

同样的该pep也支持上述各种表达式里面使用await语句,像下面这样

result = [await fun() for fun in funcs]

详细内容

同样的我们可以创建set,list,dict的异步推导式。

异步集合推导式: {i async for i in agen()};
异步列表推导式: [i async for i in agen()];
异步字典推导式: {i: i ** 2 async for i in agen()};
异步生成器推导式:(i ** 2 async for i in agen()).

和以前我们熟悉的推导式一样我们可以在使用async for来生成推导式的时候,使用条件语句if,就像下面这样

dataset = {data for line in aiter()
async for data in line
if check(data)}

需要注意的是到python3.6的时候async和await必须配合async def函数使用,不能写在异步函数之外,但是在python3.7的时候这个限制将被解除。

推导式里使用await

异步推导式

await可以用到同步表达式和异步表达式中,像下面的代码这样

result = [await fun() for fun in funcs]
result = {await fun() for fun in funcs}
result = {fun: await fun() for fun in funcs} result = [await fun() for fun in funcs if await smth]
result = {await fun() for fun in funcs if await smth}
result = {fun: await fun() for fun in funcs if await smth} result = [await fun() async for fun in funcs]
result = {await fun() async for fun in funcs}
result = {fun: await fun() async for fun in funcs} result = [await fun() async for fun in funcs if await smth]
result = {await fun() async for fun in funcs if await smth}
result = {fun: await fun() async for fun in funcs if await smth}

以上语句只能在async def函数体中使用

语句更新

该提议需要对语法级别进行一次更改:向comp_for添加可选的“async”关键字:

comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]

python 推导式AST部分将加入is_async参数。这个实际上就是说加入字典异步推导式的实现,像同步那样。

是否支持向后兼容

支持向后兼容

提供人

PEP 530 由 Guido, 2016年9月6日提出.

参考资料

[1] https://mail.python.org/pipermail/python-ideas/2016-September/042141.html

[2] https://github.com/1st1/cpython/tree/asyncomp

[3] http://bugs.python.org/issue28008

版权声明

本文章翻译整理自,pep530

Source: https://github.com/python/peps/blob/master/pep-0530.txt

最新文章

  1. Web API返回JSON数据
  2. NPOI 导入导出excel 支持 03 07
  3. AC日记——石头剪子布 openjudge 1.7 04
  4. java 中LinkedList的学习
  5. [bootstrap] 基本css样式和组件
  6. P112、面试题16:反转链表
  7. jquery图片上传
  8. (转) Friendship and inheritance
  9. (转) 学习C++ -> 向量(vector)
  10. Mac os 进行Android开发笔记(1)
  11. POJ 2217 Secretary (后缀数组)
  12. Storm中-Worker Executor Task的关系
  13. sudo apt-get update: 0% [正在等待报头]
  14. camstart API 服务器负载均衡
  15. react-fetch数据发送请求
  16. rar压缩find查找到的文件
  17. day_6.21web框架编写
  18. 【python007 -分支和循环】
  19. 装饰模式Decorator Pattern
  20. Vue2服务端渲染

热门文章

  1. Kafka吞吐量测试案例
  2. Java Bean的规范
  3. Web API中使用CORS解决跨域
  4. 端口与进程-----Window cmd命令
  5. Eclipse复制web项目怎么改
  6. 批量获取oracle的表和表字段注释【原】
  7. SpringBoot系列: Redis 共享Session
  8. 完全使用UDP登录Linux
  9. C++ WString与String互相转换
  10. Mac pro 装双系统 参考