Junior — Middle
Can you tell about different ways to use the asyncio module in Python?
sobes.tech AI
Answer from AI
The asyncio module in Python is used for writing asynchronous code that allows multiple operations to run concurrently without blocking the main thread.
Main ways to use asyncio:
-
Asynchronous functions (coroutines): declared with
async defand can useawaitto wait for other asynchronous operations. -
Running the event loop: using
asyncio.run()to start a coroutine and handle asynchronous tasks. -
Creating tasks: with
asyncio.create_task()to run a coroutine in parallel with others. -
Working with asynchronous primitives: such as queues (
asyncio.Queue), locks (asyncio.Lock), semaphores, etc.
Example of simple asynchronous code:
import asyncio
async def say_after(delay, message):
await asyncio.sleep(delay)
print(message)
async def main():
task1 = asyncio.create_task(say_after(1, "Hello"))
task2 = asyncio.create_task(say_after(2, "World"))
await task1
await task2
asyncio.run(main())
This code runs two tasks in parallel without blocking execution.