Skip to content

Instantly share code, notes, and snippets.

@jmdacruz
Forked from Morreski/timed_cache.py
Last active July 26, 2022 13:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jmdacruz/764bcaa092eefc369a8bfb90c5fe3227 to your computer and use it in GitHub Desktop.
Save jmdacruz/764bcaa092eefc369a8bfb90c5fe3227 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):
maxsize = timedelta_kwargs.pop('maxsize', 128)
typed = timedelta_kwargs.pop('typed', False)
update_delta = timedelta(**timedelta_kwargs)
next_update = datetime.utcnow() - update_delta
# Apply @lru_cache to f
f = functools.lru_cache(maxsize=maxsize, typed=typed)(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
@helix84
Copy link

helix84 commented Nov 20, 2018

Hi @jmdacruz, I added a possibility to call the cache_info() and cache_clear() methods from the underlying lru_cache:
https://gist.github.com/helix84/05ee246d6c80bc7bacdfa6a62fbff3fa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment