Last active
January 8, 2017 00:08
-
-
Save nitori/a277087fad8ef223d93315a3ed268d8d to your computer and use it in GitHub Desktop.
Like lru_cache but with a timeout instead
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
import functools | |
import time | |
def timed_cache(seconds, typed=False): | |
def _decorator(user_function): | |
cache = {} | |
sentinel = object() | |
@functools.wraps(user_function) | |
def _wraps(*args, **kwargs): | |
key = functools._make_key(args, kwargs, typed) | |
result = cache.get(key, sentinel) | |
if result is not sentinel: | |
ts, result = result | |
if time.time() < ts: | |
return result | |
result = user_function(*args, **kwargs) | |
cache[key] = (time.time() + seconds, result) | |
return result | |
return _wraps | |
return _decorator | |
@timed_cache(5) | |
def foo(): | |
return time.time() | |
""" | |
>>> foo() | |
1483834036.2725716 | |
>>> foo() | |
1483834036.2725716 | |
>>> foo() | |
1483834036.2725716 | |
>>> foo() | |
1483834036.2725716 | |
>>> foo() | |
1483834036.2725716 | |
>>> foo() | |
1483834041.4244115 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment