Python's functools module provides three interesting functions: partial, update_wrapper, and wraps.
Partial function, which can re-bind the optional parameters of the function to generate a callable partial object.
The update_wrapper function copies the _ name _, _ module _, _ Doc _, and _ dict _ of encapsulated functions to the encapsulation function.
The wraps function further encapsulates update_wrapper.
You can use the wraps function to implement a simple method blocking mechanism to implement your own cachecallhandler,
Specific implementation:
#-*-Coding: UTF-8-*-# features # Name: module 2 # purpose: # Author: ankier # created: 22-12-2012 # copyright: (c) ankier 2012 # licence: <2012 ~ 2020> # define 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): # Save result = fun (ARGs, kW) _ cache [Key] = {'value': result, 'time': time. time ()} return _ cache [Key] ['value'] Return wrap return _ cachecallhandler
Output result:
------sum----- 99
Enrich the functions of cachecallhandler and add cache expiration policies.
Implementation:
#-*-Coding: UTF-8-*-# features # Name: module 2 # purpose: # Author: ankier # created: 22-12-2012 # copyright: (c) ankier 2012 # licence: <2012 ~ 2020> # define 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): # Save result = fun (ARGs, kW) _ cache [Key] = {'value': result, 'time': time. time ()} return _ cache [Key] ['value'] Return wrap return _ cachecallhandler