From af464b45ffc744a011c426bd291ea3dd50a289d1 Mon Sep 17 00:00:00 2001 From: Tyler Goodlet Date: Sun, 25 Nov 2018 14:55:55 -0500 Subject: [PATCH] Add an async function cache with a LIFO policy Relates to #59 --- piker/_async_utils.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 piker/_async_utils.py diff --git a/piker/_async_utils.py b/piker/_async_utils.py new file mode 100644 index 00000000..ca3f5b4d --- /dev/null +++ b/piker/_async_utils.py @@ -0,0 +1,33 @@ +""" +Async utils no one seems to have built into a core lib (yet). +""" +from collections import OrderedDict + + +def alifo_cache(maxsize=128): + """Async ``cache`` with a LIFO policy. + + Implemented my own since no one else seems to have + a standard. I'll wait for the smarter people to come + up with one, but until then... + """ + cache = OrderedDict() + + def decorator(fn): + + async def wrapper(*args): + key = args + try: + return cache[key] + except KeyError: + if len(cache) >= maxsize: + # discard last added new entry + cache.popitem() + + # do it + cache[key] = await fn(*args) + return cache[key] + + return wrapper + + return decorator