How to use Asynchronous Comprehensions?

前端 未结 1 712
孤城傲影
孤城傲影 2021-01-06 03:37

I\'m trying to use Python 3.6\'s async comprehensions in a MacOS Sierra (10.12.2), but I\'m receiving a SyntaxError.

Here is the code I\'ve tried:

相关标签:
1条回答
  • 2021-01-06 03:56

    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.

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

    Asynchronous comprehensions are only allowed inside an async def function.

    Similarly, for using await in comprehensions:

    This is only valid in async def function body.

    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:

    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.

    0 讨论(0)
提交回复
热议问题