Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LRU cache that invalidates every minute
from functools import lru_cache, wraps
from datetime import datetime
def lru_cache_by_minute(size):
""" Decorator that caches the result of `f` during the current minute """
def real_decorator(f):
# create a cached function that wraps f but adds a minute argument
# the size is the number of entries in the cache
@lru_cache(size)
@wraps(f)
def inner(minute, *args, **kwargs):
return f(*args, **kwargs)
# calls the cached function with the current minute
# everytime the current minute changes, the cache is automagically invalidated
@wraps(inner)
def outer(*args, **kwargs):
now_minute = datetime.now().replace(second=0, microsecond=0)
return inner(now_minute, *args, **kwargs)
return outer
return real_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.