What AsyncIO is a coroutine function
async def expression.What is AsyncIO event loop
The asyncio event loop is a single-threaded scheduler that runs coroutine-based tasks by switching between them whenever their awaited I/O or timers become ready. It uses OS-level event notification (like epoll on linux) to drive cooperative concurrency.
Coroutine function vs coroutine object
coroutine Python object has methods, such as send() and close(). It is a type.awaitable. This means it is a Python type that implements the await() method.async def custom_coro():
await asyncio.sleep(1)
coro = custom_coro()
print(type(coro))
# <class 'coroutine'>Basic way to start new event loop for a program (that will execute main)
import asyncio
async def main():
await custom_coro()
asyncio.run(main())Create event loop (low level method)
loop = asyncio.new_event_loop()
What is Task
create_task() function wraps an awaitable object into a higher-level Task object that’s scheduled to run concurrently on the event loop in the background. In contrast, awaiting a coroutine runs it immediately, pausing the execution of the caller until the awaited coroutine finishes.How to create task for t coroutine, called "MyTask"
task = asyncio.create_task(task_coroutine(), name='MyTask')
How to see if task was finished or cancelled?
task.done() task.cancelled()
How to get results of a task and handle errors
try: # Get the return value from the wrapped coroutine value = task.result() except asyncio.CancelledError: # Task was canceled except asyncio.InvalidStateError: # Task is not yet done except Exception: # Task failed and there is no result
How to get list of all tasks
tasks = asyncio.all_tasks()
How to group awaitables to be treated as a single awaitable
results = await asyncio.gather(coro1(), asyncio.create_task(coro2()))
Wait for list of tasks to complete.
- All of them
- Only first
- First error
done, pending = await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED) # default first_done, rest = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) first_error, rest = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
Loop over async iterator (like async generator)
async for i in powers_of_two(5):
g.append(i)How to work with async resource with context manager (with)
async with session.get(url) as response:
print(f"{url}: status -> {response.status}")How to use async queue?
- Add elements
- Remove elements
queue = asyncio.Queue() queue.put(user) user = await queue.get()
How to sleep for 1 second (async)
asyncio.sleep(1)