Skip to content

Instantly share code, notes, and snippets.

@jaredLunde
Last active June 7, 2022 10:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredLunde/7a118c03c3e9b925f2bf to your computer and use it in GitHub Desktop.
Save jaredLunde/7a118c03c3e9b925f2bf to your computer and use it in GitHub Desktop.
An LRU cache for asyncio coroutines in Python 3.5
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
@jaredLunde
Copy link
Author

@async_lru(1024)
async def slow_coroutine(*args, **kwargs):
    return await some_other_slow_coroutine()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment