How to use asynchronous methods?

I try to use Python 3.6 async solutions on MacOS Sierra (10.12.2), but I get SyntaxError .

Here is the code I 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 get a syntax error for asynchronous loops :

 result = [] async for i in aiter(): if i % 2: result.append(i) 

All code is copied / pasted from 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 >>> 
+5
source share
1 answer

This behaves as expected. The problem is that these forms of understanding are only allowed inside async def functions. Outside (at the top level, as indicated in your REPL), they raise a SyntaxError as defined.

This is indicated in the PEP specification section, namely for asynchronous concepts :

Asynchronous understanding is only allowed inside the async def function.

Similarly, to use await in understanding :

This is only valid in the async def tag.

As for async loops , you will need both an object corresponding to the corresponding interface (defines __aiter__ ) and placed inside the async def function. Again, this is indicated in the corresponding PEP:

It is a TypeError to pass the regular __aiter__ method __aiter__ to async for . SyntaxError use async for outside the async def function.

+6
source

Source: https://habr.com/ru/post/1015051/


All Articles