Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Asynchronous Comprehensions?

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:

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)

All code is copy/paste from the PEP.

Terminal Output:

>>> 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
>>> 
like image 712
João Farias Avatar asked Dec 24 '16 22:12

João Farias


Video Answer


1 Answers

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.

like image 172
Dimitris Fasarakis Hilliard Avatar answered Oct 27 '22 07:10

Dimitris Fasarakis Hilliard