This post discusses python asyncio module.
Asynchronous IO is a language-agnostic paradigm that has implementations across a host of programming languages.
asyncio package in python provides API to run
async IO gives you a feeling of concurrency despite using a single thread in a single process. Asynchronous routines are able to “pause” while waiting on their ultimate result and let other routines run in the meantime.
import asyncio async def count(): print("One") await asyncio.sleep(1) print("Two") async def main(): await asyncio.gather(count(), count(), count()) if __name__ == "__main__": import time s = time.perf_counter() asyncio.run(main())
This simple code block above, when run, will output:
one one one two two two
async defintroduces either a native
asynchronous generator. To call a coroutine function, you must
awaitit to get its results.
awaitpasses function control back to event loop. If Python encounters an
await f()expression in the scope of
g(), this is how
awaittells the event loop, Suspend execution of g() until whatever I’m waiting on. It is a syntax error to use
It is less common to use
async defblock. This creates an
When we use
f()has to be an object that is awaitable. For now, just know that an awaitable object is another coroutine.
A coroutine is a specialized version of a Python generator function.