Concurrency and asyncio: Python snippets
Part of 30 Seconds of Python. Source: snippets/concurrency.py.
Every example below is run as a test.
parallel_map
Run fn over items on a thread pool (good for I/O), keeping order.
def parallel_map(fn, items, workers=8):
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(fn, items))
>>> parallel_map(lambda x: x * 2, [1, 2, 3])
[2, 4, 6]
gather_limited
Await coroutines with at most limit running at once; results keep order.
async def gather_limited(coros, limit):
sem = asyncio.Semaphore(limit)
async def run(coro):
async with sem:
return await coro
return await asyncio.gather(*(run(c) for c in coros))
>>> async def double(x):
... await asyncio.sleep(0)
... return x * 2
>>> asyncio.run(gather_limited([double(i) for i in range(5)], limit=2))
[0, 2, 4, 6, 8]
with_timeout
Await coro but give up after seconds and return default.
async def with_timeout(coro, seconds, default=None):
try:
return await asyncio.wait_for(coro, seconds)
except asyncio.TimeoutError:
return default
>>> asyncio.run(with_timeout(asyncio.sleep(10, 'late'), 0.01, default='timeout'))
'timeout'
run_sync
Run a coroutine from regular code (no running event loop required).
def run_sync(coro):
return asyncio.run(coro)
>>> async def hello():
... return 'hi'
>>> run_sync(hello())
'hi'