Created
October 29, 2020 16:05
-
-
Save easysugar/95237f694b0fc698a1727819e7e8d996 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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