Python Async
July 30, 2020 |
python,
programming
- Related pages
Important keywords #
Asynchronous IO (async IO)
Language-agnostic paradigm (model)coroutine
A Python (sort of generator function)async/await
Python keywords used to defined a coroutineasyncio
Python package that provides an API for running/managing coroutines
Coroutine #
A coroutine allows a function to pause before returning or indirectly call another coroutine for some time, for example:
import asyncio
import time
async def count(n):
print(f"n is {n}")
await asyncio.sleep(n)
print(f"Returning from {n}")
async def main():
await asyncio.gather(count(1), count(2), count(3))
m = time.perf_counter()
asyncio.run(main())
elapsed = time.perf_counter() - m
print(f"Executed in {elapsed:0.2f} seconds.")
n is 1
n is 2
n is 3
Returning from 1
Returning from 2
Returning from 3
Executed in 3.00 seconds.