Skip to content

Instantly share code, notes, and snippets.

@achimnol
Created October 28, 2017 06:45
Show Gist options
  • Save achimnol/da6983838b31f6f188d539b9ce9ea5ba to your computer and use it in GitHub Desktop.
Save achimnol/da6983838b31f6f188d539b9ce9ea5ba to your computer and use it in GitHub Desktop.
async getitem with futures
import asyncio
class MyAsyncDict:
async def async_getitem(self, fut, key):
try:
await asyncio.sleep(0.5)
raise RuntimeError('oops')
except Exception as e:
fut.set_exception(e)
else:
fut.set_result(1)
def __getitem__(self, key):
loop = asyncio.get_event_loop()
fut = loop.create_future()
loop.create_task(self.async_getitem(fut, key))
return fut
async def myfunc():
a = MyAsyncDict()
print(await a['x'])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(myfunc())
finally:
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment