Last active
September 3, 2024 00:29
-
-
Save Morreski/c1d08a3afa4040815eafd3891e16b945 to your computer and use it in GitHub Desktop.
Python lru_cache with timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
args = [tuple(v) if isinstance(v, list) else v for v in args]
for args too