gpt4 book ai didi

python - 如何使用异步理解?

转载 作者:太空狗 更新时间:2023-10-30 00:59:27 25 4
gpt4 key购买 nike

我正在尝试使用 Python 3.6's async comprehensions在 MacOS Sierra (10.12.2) 中,但我收到了一个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
>>>

最佳答案

这符合预期。问题是这些形式的理解只允许在内部 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 ,您将需要一个符合必要接口(interface)(定义 __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.

关于python - 如何使用异步理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41317309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com