async — Intermediate Playground
Declares an asynchronous coroutine function or context manager
Python Playground
import asyncio
async def task(name, delay):
print(f" {name}: starting")
await asyncio.sleep(delay)
print(f" {name}: done after {delay}s")
return f"{name}-result"
async def main():
# Run tasks concurrently with gather
results = await asyncio.gather(
task("A", 0.02),
task("B", 0.01),
task("C", 0.03),
)
print(f"Results: {results}")
asyncio.run(main())
Output
Click "Run" to execute your code
asyncio.gather() runs multiple coroutines concurrently. Unlike threads, async switches tasks at await points, not preemptively.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?