Skip to content

Instantly share code, notes, and snippets.

@h0rn3t
Created January 23, 2021 11:05
Show Gist options
  • Save h0rn3t/69697974a1e487f90041d5401e508da4 to your computer and use it in GitHub Desktop.
Save h0rn3t/69697974a1e487f90041d5401e508da4 to your computer and use it in GitHub Desktop.
timed_lru_cache
from functools import lru_cache, wraps
from datetime import datetime, timedelta
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_func(*args, **kwargs):
if datetime.utcnow() >= func.expiration:
func.cache_clear()
func.expiration = datetime.utcnow() + func.lifetime
return func(*args, **kwargs)
return wrapped_func
return wrapper_cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment