Skip to content

Instantly share code, notes, and snippets.

@zyd14
Last active August 18, 2023 00:02
Show Gist options
  • Save zyd14/748858448c97780843d62f6c0151a6ad to your computer and use it in GitHub Desktop.
Save zyd14/748858448c97780843d62f6c0151a6ad to your computer and use it in GitHub Desktop.
Timed LRU Cache
# 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