直接上源码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
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)
# do we have it already?
if key in cache and not is_obsolete(cache[key], duration):
print 'we got a winner'
return cache[key]['value']
# computing
res