Last active
August 8, 2018 11:48
-
-
Save t00n/82ea5b3a35bff970c95bc8ab928d86dd to your computer and use it in GitHub Desktop.
LRU cache that invalidates every minute
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
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