Last active
August 18, 2023 00:02
-
-
Save zyd14/748858448c97780843d62f6c0151a6ad to your computer and use it in GitHub Desktop.
Timed LRU Cache
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 RealPython blog. | |
from functools import lru_cache, wraps | |
from datetime import datetime, timedelta | |
# Note: this will clear whole cache each time expiration is reached. Should adapt to expire items independently when they expire | |
def timed_lru_cache(seconds: int, maxsize: int = 128): | |
def wrapper_cache(func): | |
func = lru_cache(maxsize=maxsize)(func) | |
func.lifetime = timedelta(seconds=seconds) | |
func.expiration = datetime.utcnow() + func.lifetime | |
@wraps(func) | |
def wrapped(*args, **kwargs): | |
if datetime.utcnow() >= func.expiration: | |
func.cache_clear() | |
func.expiration = datetime.utcnow() + func.lifetime | |
wrapped.cache_info = func.cache_info() | |
return func(*args, **kwargs) | |
return wrapped | |
return wrapper_cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment