Last active
November 2, 2017 02:18
-
-
Save allenyang79/c4f443d89169d4821efa2bb6020ecd96 to your computer and use it in GitHub Desktop.
python memorize function for cache
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 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