如何使用异步理解?

How to use Asynchronous Comprehensions?

我正在尝试在 MacOS Sierra (10.12.2) 中使用 Python 3.6's async comprehensions,但我收到 SyntaxError.

这是我试过的代码:

print( [ i async for i in range(10) ] )
print( [ i async for i in range(10) if i < 4 ] )
[i async for i in range(10) if i % 2]

我收到 async loops 的语法错误:

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

所有代码均来自 PEP copy/paste。

终端输出:

>>> print([i for i in range(10)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print([i async for i in range(10)])            
  File "<stdin>", line 1
    print([i async for i in range(10)])
                  ^
SyntaxError: invalid syntax
>>> print([i async for i in range(10) if i < 4])
  File "<stdin>", line 1
    print([i async for i in range(10) if i < 4])
                 ^
SyntaxError: invalid syntax
>>> 

这符合预期。问题是这些形式的理解只允许 inside async def 函数。在外部(即在您的 REPL 中输入的顶层),它们按定义提出 SyntaxError

这在 PEP 的规范部分中有说明,具体来说,for asynchronous comprehensions:

Asynchronous comprehensions are only allowed inside an async def function.

同样,使用await in comprehensions

This is only valid in async def function body.

至于 async loops,您将需要一个符合必要接口(定义 __aiter__)并放置在 async def 函数中的对象。同样,这在相应的 PEP 中指定:

It is a TypeError to pass a regular iterable without __aiter__ method to async for. It is a SyntaxError to use async for outside of an async def function.