Python的functools模組, 提供了3個有趣函數, partial, update_wrapper 和wraps 。
partial函數,它可以重新綁定函數的選擇性參數,產生一個callable的partial對象。
update_wrapper函數,把被封裝函數的__name__、__module__、__doc__和 __dict__都複製到封裝函數去。
wraps函數,對update_wrapper更進一步封裝。
可以利用wraps函數,實現簡單的方法攔截機制,來實現自己的cacheCallHandler,
具體實現:
#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name: 模組2# Purpose:## Author: ankier## Created: 22-12-2012# Copyright: (c) Ankier 2012# Licence: <2012~2020>#-------------------------------------------------------------------------------import timeimport hashlibimport pickleimport sysfrom functools import wraps_Cache ={}def __HashParamsKey(function, args, kw): glos = function.func_globals package = glos['__package__'] model = glos['__name__'] methodName = function.func_name key = pickle.dumps((package, model, methodName, args, kw)) return hashlib.sha1(key).hexdigest()def __IsObsolete(entry, duration): return time.time() - entry['time'] > durationdef CacheCallHandler(duration = sys.maxint): def _CacheCallHandler(fun): @wraps(fun) def wrap(args, kw): key = __HashParamsKey(fun, args, kw) if key not in _Cache or __IsObsolete(_Cache[key], duration): #儲存結果 result = fun(args, kw) _Cache[key] = {'value': result, 'time': time.time()} return _Cache[key]['value'] return wrap return _CacheCallHandler
輸出結果:
------sum----- 99
豐富CacheCallHandler的功能,加上cache到期策略。
實現:
#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name: 模組2# Purpose:## Author: ankier## Created: 22-12-2012# Copyright: (c) Ankier 2012# Licence: <2012~2020>#-------------------------------------------------------------------------------import timeimport hashlibimport pickleimport sysfrom functools import wraps_Cache ={}def __HashParamsKey(function, args, kw):
glos = function.func_globals
package = glos['__package__']
model = glos['__name__']
methodName = function.func_name
key = pickle.dumps((package, model, methodName, args, kw))
return hashlib.sha1(key).hexdigest()
def __IsObsolete(entry, duration): return time.time() - entry['time'] > durationdef CacheCallHandler(duration = sys.maxint): def _CacheCallHandler(fun): @wraps(fun) def wrap(args, kw): key = __HashParamsKey(fun, args, kw) if key not in _Cache or __IsObsolete(_Cache[key], duration): #儲存結果 result = fun(args, kw) _Cache[key] = {'value': result, 'time': time.time()} return _Cache[key]['value'] return wrap return _CacheCallHandler