Skip to content

Instantly share code, notes, and snippets.

@joshz
Created January 6, 2012 14:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshz/1570794 to your computer and use it in GitHub Desktop.
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
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