From 61ccb8230913e3eff8285c1387c20354e15fcc55 Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Mon, 22 Jun 2020 18:44:53 +0300 Subject: Async Cache: Make cache handle different caches better --- bot/cogs/doc.py | 2 +- bot/utils/cache.py | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/bot/cogs/doc.py b/bot/cogs/doc.py index ff60fc80a..173585976 100644 --- a/bot/cogs/doc.py +++ b/bot/cogs/doc.py @@ -187,7 +187,7 @@ class Doc(commands.Cog): self.base_urls.clear() self.inventories.clear() self.renamed_symbols.clear() - async_cache.cache = OrderedDict() + async_cache.cache["get_symbol_embed"] = OrderedDict() # Run all coroutines concurrently - since each of them performs a HTTP # request, this speeds up fetching the inventory data heavily. diff --git a/bot/utils/cache.py b/bot/utils/cache.py index 96e1aef95..37c2b199c 100644 --- a/bot/utils/cache.py +++ b/bot/utils/cache.py @@ -11,21 +11,23 @@ def async_cache(max_size: int = 128, arg_offset: int = 0) -> Callable: An offset may be optionally provided to be applied to the coroutine's arguments when creating the cache key. """ - # Assign the cache to the function itself so we can clear it from outside. - async_cache.cache = OrderedDict() + # Make global cache as dictionary to allow multiple function caches + async_cache.cache = {} def decorator(function: Callable) -> Callable: """Define the async_cache decorator.""" + async_cache.cache[function.__name__] = OrderedDict() + @functools.wraps(function) async def wrapper(*args) -> Any: """Decorator wrapper for the caching logic.""" key = ':'.join(str(args[arg_offset:])) if key not in async_cache.cache: - if len(async_cache.cache) > max_size: - async_cache.cache.popitem(last=False) + if len(async_cache.cache[function.__name__]) > max_size: + async_cache.cache[function.__name__].popitem(last=False) - async_cache.cache[key] = await function(*args) - return async_cache.cache[key] + async_cache.cache[function.__name__][key] = await function(*args) + return async_cache.cache[function.__name__][key] return wrapper return decorator -- cgit v1.2.3