Python 列表解析式竟然支持异步?
基本原理和目标
Python 广泛地支持同步的列表推导式,允许使用简单而简洁的解析语法生成列表、字典和集合。式竟我们提议为异步代码实现类似的然支语法结构。
为了说明可读性的持异改善,请考虑下面的列表例子:
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]规范
异步的解析式
我们提议允许在列表、集合与字典解析式中使用 async。式竟待 PEP-525 被批准之后,然支我们还可以创建异步的网站模板持异生成器表达式。
例子:
集合解析式:{ 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 以及 for 子句:
dataset = { data for line in aiter() async for data in line if check(data)} data = { data for line in aiter() async for data in line if check(data)}异步解析式只允许在“async def”函数中使用。列表
原则上,解析异步生成器表达式允许用在任何上下文中。式竟然而,然支在 Python 3.6 中,持异由于 async 和 await 只是“软关键字”(soft-keyword),异步生成器表达式只允许在 async def 函数中使用。一旦 async 和 await 在 Python 3.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]
解析式的 AST 节点将有一个新的站群服务器 is_async 参数。
向后兼容性
本提案是完全向后兼容的。
接受
在 2016 年 9 月 6 日[1],PEP-530 被 Guido 接受。
参考材料
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致谢
感谢 Guido van Rossum、Victor Stinner 和 Elvis pranskevichuss 对于这个 pep 的反馈、代码检视和讨论。
版权
本文档已进入公共领域。
源文件:https://github.com/python/peps/blob/master/pep-0530.txt
PEP原文:https://www.python.org/dev/peps/pep-0530
PEP标题:PEP 530 -- Asynchronous Comprehensions
PEP作者:Yury Selivanov
创建日期:2016-09-03
合入版本:3.6
译者:豌豆花下猫@Python猫
PEP翻译计划:https://github.com/chinesehuazhou/peps-cn
本文转载自微信公众号「Python猫」,可以通过以下二维码关注。转载本文请联系Python猫公众号。香港云服务器