To make asynchronous programming more straightforward, the await
and async
keywords were introduced in Python 3.5, along with the coroutine
type. The await
call is almost equivalent to yield from, as its goal is to let you call a coroutine from another coroutine.
The difference is that you can't use the await
call to call a generator (yet).
The async
keyword marks a function, a for
or a with
loop, as being a native coroutine, and if you try to use that function, you will not retrieve a generator but a coroutine object.
The native coroutine type that was added in Python is like a fully symmetric generator, but all the back and forth is delegated to an event loop, which is in charge of coordinating the execution.
In the example that follows, the asyncio
library is used to run main()
, which, in turn, calls several coroutines in parallel:
import asyncio async def compute(): for i in range(5): print('compute %d' % i) await asyncio.sleep(.1)...