from functools import wraps def intercept(target,**trigger): def decorator(func): names = getattr(func,'_names',None) if names is None: code = func.func_code names = code.co_varnames[:code.co_argcount] @wraps(func) def decorated(*args,**kwargs): all_args = kwargs.copy() for n,v in zip(names,args): all_args[n] = v for k,v in trigger.iteritems(): if k in all_args and all_args[k] != v: break else: return target(all_args) return func(*args,**kwargs) decorated._names = names return decorated return decorator
Example:
def interceptor1(kwargs): print 'Intercepted by #1!' def interceptor2(kwargs): print 'Intercepted by #2!' def interceptor3(kwargs): print 'Intercepted by #3!' @intercept(interceptor1,arg1=20,arg2=5)
functools.wraps does what a "simple decorator" does on the wiki; Updates __doc__ , __name__ and other attributes of the decorator.
source share