编程语言
首页 > 编程语言> > python – 如何使用异步理解?

python – 如何使用异步理解?

作者:互联网

我试图在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复制/粘贴的.

终端输出:

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

解决方法:

这表现得如预期.问题是这些形式的理解只允许在异步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.

对于异步循环,您需要一个符合必要接口的对象(定义__aiter__)并放置在异步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.

标签:python-3-6,python,python-3-x,asynchronous,async-await
来源: https://codeday.me/bug/20191008/1871188.html