Skip to content

Instantly share code, notes, and snippets.

@t00n
Last active August 8, 2018 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t00n/82ea5b3a35bff970c95bc8ab928d86dd to your computer and use it in GitHub Desktop.
Save t00n/82ea5b3a35bff970c95bc8ab928d86dd to your computer and use it in GitHub Desktop.
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