Skip to content

Instantly share code, notes, and snippets.

@phizaz
Last active December 20, 2016 03:48
Show Gist options
  • Save phizaz/999514f1567f13af3bc35370ea39905f to your computer and use it in GitHub Desktop.
Save phizaz/999514f1567f13af3bc35370ea39905f to your computer and use it in GitHub Desktop.
Python awaitasync: wait both async and sync in one function
import asyncio
def unzip(l):
return zip(*l)
def merge(*itrs):
from itertools import chain
return chain.from_iterable(itrs)
async def wait(l):
async def wait_each(x):
if asyncio.iscoroutine(x):
return await x
return x
_all = list(map(wait_each, l))
vals = await asyncio.gather(*_all)
return vals
async def plus(a, b):
await asyncio.sleep(1)
return a + b
async def test():
l = await wait([1, 0, plus(1, 2), plus(2, 5)])
print(l)
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment