async and await let Python pause one task while waiting and continue another task in the same event loop.
Async code is useful for I/O-heavy work such as many network requests, sockets, or cooperative background tasks.
Do not use async just because it looks advanced. Use it when libraries and workload fit the event-loop model.
An async def function returns a coroutine. It runs when awaited or passed into the event loop.
import asyncio
async def greet():
await asyncio.sleep(0)
return "Hello async"
message = asyncio.run(greet())
print(message)
Hello async
asyncio.run starts the event loop and returns the coroutine result.
asyncio.gather waits for multiple awaitable tasks and returns their results together.
import asyncio
async def load(name):
await asyncio.sleep(0)
return name.upper()
async def main():
results = await asyncio.gather(load("csv"), load("json"))
print(results)
asyncio.run(main())
['CSV', 'JSON']
Both coroutines are scheduled and gathered by the event loop.
Try this next
0 of 3 completed
Only for the right kind of waiting-heavy workload. It does not automatically speed up ordinary calculations.
You usually get a coroutine object instead of the final result, and the intended work may not run.
Advanced programs can, but beginners should learn each model separately first.
Explore 500+ free tutorials across 20+ languages and frameworks.