1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
""" Created on 4/20/16
@author: Jiezhi.G@gmail.com
My Blog: jiezhi.github.io
Reference: <Expert Python Programming> Chapter 2--Decorators_Proxy Page.53 """ import time import hashlib import pickle
cache = {}
def is_obsolete(entry, duration): return time.time() - entry['time'] > duration
def compute_key(function, args, kw): key = pickle.dumps((function.func_name, args, kw)) return hashlib.sha1(key).hexdigest()
def memoize(duration=10): def _memoize(function): def __memoize(*args, **kw): key = compute_key(function, args, kw)
if key in cache and not is_obsolete(cache[key], duration): print 'we got a winner' return cache[key]['value']
result = function(*args, **kw)
cache[key] = {'value': result, 'time': time.time()} return result
return __memoize return _memoize
@memoize() def very_very_very_complex_stuff(a, b): return a + b
if __name__ == '__main__': print very_very_very_complex_stuff(2, 2) print cache print very_very_very_complex_stuff(2, 2)
|