async — Advanced Playground
Declares an asynchronous coroutine function or context manager
Python Playground
import asyncio
class AsyncTimer:
def __init__(self, label):
self.label = label
async def __aenter__(self):
print(f" [{self.label}] Starting")
self.start = asyncio.get_event_loop().time()
return self
async def __aexit__(self, *args):
elapsed = asyncio.get_event_loop().time() - self.start
print(f" [{self.label}] Done ({elapsed:.4f}s)")
async def main():
async with AsyncTimer("task"):
await asyncio.sleep(0.01)
# Semaphore for concurrency limiting
sem = asyncio.Semaphore(2)
async def limited_task(n):
async with sem:
print(f" Task {n} running")
await asyncio.sleep(0.01)
await asyncio.gather(*[limited_task(i) for i in range(5)])
asyncio.run(main())
Output
Click "Run" to execute your code
async with calls __aenter__ and __aexit__ which can themselves await. Semaphores limit how many coroutines run a section concurrently.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?