关于python:Python-列表解析式竟然支持异步

3次阅读

共计 2070 个字符,预计需要花费 6 分钟才能阅读完成。

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

摘要

PEP-492 和 PEP-525 通过 async/await 语法,引入了对原生协程和异步生成器的反对。本 pep 提议给列表、汇合、字典解析式和生成器表达式增加异步的版本。

基本原理和指标

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

正文完
 0