Skip to content

Instantly share code, notes, and snippets.

@bendog
Created September 10, 2018 05:03
Show Gist options
  • Select an option

  • Save bendog/149d33149bfbbd0bb6df35fe9007fb3f to your computer and use it in GitHub Desktop.

Select an option

Save bendog/149d33149bfbbd0bb6df35fe9007fb3f to your computer and use it in GitHub Desktop.

Revisions

  1. bendog created this gist Sep 10, 2018.
    23 changes: 23 additions & 0 deletions timed_cache_helper.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import functools
    import datetime


    def timed_cache(maxsize=128, typed=False, **timedelta_kwargs):
    def _wrapper(f):
    update_delta = datetime.timedelta(**timedelta_kwargs)
    next_update = datetime.datetime.utcnow() - update_delta
    # Apply @lru_cache to f with no cache size limit
    f = functools.lru_cache(maxsize=maxsize, typed=typed)(f)

    @functools.wraps(f)
    def _wrapped(*args, **kwargs):
    nonlocal next_update
    now = datetime.datetime.utcnow()
    if now >= next_update:
    f.cache_clear()
    next_update = now + update_delta
    return f(*args, **kwargs)

    return _wrapped

    return _wrapper