With asyncio
the provided @asyncio.coroutine
, you can mark a generator as the coroutine type, and then implement the asynchronous operation within Coroutine by yield from
calling another coroutine.
To simplify and better identify asynchronous IO, the new syntax is introduced starting with Python 3.5 async
await
, which makes Coroutine's code easier to read.
Note that, async
and the await
new syntax for coroutine, to use the new syntax, you only need to do a two-step simple substitution:
- To
@asyncio.coroutine
Replace with async
;
yield from
Replace with a await
.
Let's compare the code in the previous section:
@asyncio. Coroutinedef Hello (): print ("Hello world! " ) yield from Asyncio.sleep (1) print (" Hello again! ")
Rewrite the following in the new syntax:
Async def hello (): print ("Hello world! " ) await asyncio.sleep (1) print ("Hello again! ")
The rest of the code remains the same.
Summary
Python begins with the 3.5 version asyncio
async
await
of the new syntax provided;
Note that the new syntax can only be used in Python 3.5 and later, and if you use version 3.4, you still need to use the previous section of the scenario.
65 async/await