Skip to content

Instantly share code, notes, and snippets.

@easysugar
Created October 29, 2020 16:05
Show Gist options
  • Save easysugar/95237f694b0fc698a1727819e7e8d996 to your computer and use it in GitHub Desktop.
Save easysugar/95237f694b0fc698a1727819e7e8d996 to your computer and use it in GitHub Desktop.
import asyncio
futures = {}
def async_future_cache(func):
async def wrapped(*args, **kwargs):
if args in futures:
return await futures[args]
f = asyncio.Future()
futures[args] = f
result = await func(*args, **kwargs)
f.set_result(result)
futures.pop(args)
return result
return wrapped
# example
import random
@async_future_cache
async def my_func(key):
print('running my func')
await asyncio.sleep(0.1)
return random.random()
await asyncio.gather(*[my_func(123) for i in range(10)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment