如何使用异步理解? [英] How to use Asynchronous Comprehensions?
问题描述
我正在尝试使用 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 for
是SyntaxError
.
It is a
TypeError
to pass a regular iterable without__aiter__
method toasync for
. It is aSyntaxError
to useasync for
outside of anasync def
function.
这篇关于如何使用异步理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!