def decorator_with_args(decf): def _inner(*dec_args): def _decorated(realf): def _inner2(*args,**kwargs): return decf(realf,*(dec_args + args),**kwargs) return _inner2 return _decorated return _inner def decorator(decf): def _decorated(realf): def _inner(*args,**kwargs): return decf(realf,*args,**kwargs) return _inner return _decorated # A decorator without parameters is a function # that takes a function as single argument and # returns a function of the same signature as # given. # # A decorator with parameters is a function that # takse those parameters and returns a decorator # without parameters as defined above. # # An argument-taking meta-decorator is a # decorator that takes a function and returns a # decorator as if it where defined as above @decorator_with_args def pre(real_fun,pre_fun,*args,**kwargs): pre_fun(*args,**kwargs) return real_fun(*args,**kwargs) @decorator def post(real_fun,*args,**kwargs): ret = real_fun(*args,**kwargs) print "AFTER!" return ret def before(*args,**kwargs): print "BEFORE!" print "args = " + repr(args) print "kwargs = " + repr(kwargs) @pre(before) @post def mainfun(x,y,a=True,b=False): print "MAIN!" print "x = %s, y = %s" % (x,y) print "a = %s, b = %s" % (a,b)