Skip to content

Instantly share code, notes, and snippets.

@sthagen
Forked from Morreski/timed_cache.py
Created March 1, 2022 13:18
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 sthagen/6648c01c8c4c9ccb893b8435712439dd to your computer and use it in GitHub Desktop.
Save sthagen/6648c01c8c4c9ccb893b8435712439dd to your computer and use it in GitHub Desktop.
Python lru_cache with timeout
from datetime import datetime, timedelta
import functools
def timed_cache(**timedelta_kwargs):
def _wrapper(f):
update_delta = timedelta(**timedelta_kwargs)
next_update = datetime.utcnow() + update_delta
# Apply @lru_cache to f with no cache size limit
f = functools.lru_cache(None)(f)
@functools.wraps(f)
def _wrapped(*args, **kwargs):
nonlocal next_update
now = datetime.utcnow()
if now >= next_update:
f.cache_clear()
next_update = now + update_delta
return f(*args, **kwargs)
return _wrapped
return _wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment