如何使用异步理解?

问题描述:

我正在尝试使用 Python 3.6的异步理解在MacOS Sierra(10.12.2)中,但是我收到了SyntaxError.

I'm trying to use Python 3.6's async comprehensions in a MacOS Sierra (10.12.2), but I'm receiving a 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]

我收到异步循环的语法错误:>

I am receiving a syntax error for async loops:

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

所有代码都是从PEP复制/粘贴.

All code is copy/paste from the PEP.

端子输出:

>>> 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
>>> 

此行为符合预期.问题是这些理解的形式只允许在内部 async def函数中使用.在外部(即,在REPL中输入的*),它们将按定义的方式产生SyntaxError.

This behaves as expected. The issue is that these forms of comprehensions are only allowed inside async def functions. Outside (i.e in the top-level as entered in your REPL), they raise a SyntaxError as defined.

这在PEP的规范部分中进行了说明,特别是用于异步理解:

This is stated in the specification section of the PEP, specifically, for asynchronous comprehensions:

异步理解只允许在async def函数内部使用.

Asynchronous comprehensions are only allowed inside an async def function.

类似地,在理解中使用 await :

Similarly, for using await in comprehensions:

这仅在async def函数主体中有效.

This is only valid in async def function body.

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

As for async loops, you'll need both an object that conforms to the necessary interface (defines __aiter__) and placed inside an async def function. Again, this is specified in the corresponding PEP:

TypeError是将不带__aiter__方法的常规可迭代对象传递给async for的功能.在async def函数之外使用async forSyntaxError.

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.