Last active
June 7, 2022 10:09
-
-
Save jaredLunde/7a118c03c3e9b925f2bf to your computer and use it in GitHub Desktop.
An LRU cache for asyncio coroutines in Python 3.5
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 | |
import functools | |
from collections import OrderedDict | |
def async_lru(size=100): | |
cache = OrderedDict() | |
def decorator(fn): | |
@functools.wraps(fn) | |
async def memoizer(*args, **kwargs): | |
key = str((args, kwargs)) | |
try: | |
cache[key] = cache.pop(key) | |
except KeyError: | |
if len(cache) >= size: | |
cache.popitem(last=False) | |
cache[key] = await fn(*args, **kwargs) | |
return cache[key] | |
return memoizer | |
return decorator |
Author
jaredLunde
commented
Mar 24, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment