Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Last active November 2, 2017 02:18
Show Gist options
  • Select an option

  • Save allenyang79/c4f443d89169d4821efa2bb6020ecd96 to your computer and use it in GitHub Desktop.

Select an option

Save allenyang79/c4f443d89169d4821efa2bb6020ecd96 to your computer and use it in GitHub Desktop.
python memorize function for cache
import functools
import inspect
import time
import random
def memorize(keyfn, scenario='default', timeout=300):
def wrapper(fn):
_cached = {}
functools.wraps(fn)
def wrapped(*args, **kw):
now = time.time()
key = keyfn(fn, *args, **kw)
if key in _cached:
(expire_at, result) = _cached[key]
if now < expire_at:
return result
result = fn(*args, **kw)
if scenario == 'default':
expire_at = now + timeout
elif scenario == 'this-hour':
expire_at = now + (3600 - (now % 3600))
else:
raise Exception('unknow memorize scenario')
_cached[key] = (expire_at, result)
return result
def purge_cache():
"""default is clear all."""
for k in _cached.keys():
del _cached[k]
return
wrapped._cached = _cached
wrapped.purge_cache = purge_cache
return wrapped
return wrapper
@memorize(keyfn=lambda fn, *args, **kw: args[0], timeout=1)
def foo(n):
return n + random.random()
print foo(2)
time.sleep(0.5)
print foo(2)
time.sleep(1)
print foo(2)
print foo(2)
foo.purge_cache()
print foo(2)
print foo(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment