Skip to content

Instantly share code, notes, and snippets.

@achimnol achimnol/example.py
Created Oct 28, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.