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 to async for. It is a SyntaxError to use async for outside of an async def function. 这篇关于如何使用异步理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-19 01:51