Created
January 6, 2012 14:16
-
-
Save joshz/1570794 to your computer and use it in GitHub Desktop.
Memoizing decorator, caches function's return value, expires after ttl time in seconds or ctl calls - Python
This file contains hidden or 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 time | |
class memoized(object): | |
def __init__(self, ctl=3, ttl=2): | |
self.cache = {} | |
self.ctl = ctl | |
self.ttl = ttl | |
self._call_count = 1 | |
def __call__(self, func): | |
def _memoized(*args): | |
self.func = func | |
now = time.time() | |
try: | |
value, last_update = self.cache[args] | |
age = now - last_update | |
if self._call_count >= self.ctl or \ | |
age > self.ttl: | |
self._call_count = 1 | |
raise AttributeError | |
self._call_count += 1 | |
return value | |
except (KeyError, AttributeError): | |
value = self.func(*args) | |
self.cache[args] = (value, now) | |
return value | |
except TypeError: | |
return self.func(*args) | |
return _memoized |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment